C 程式設計的趣聞


在這裡,將介紹 C 程式設計的一些有趣的事實。例如:

  • 有時,某些 switch 語句的 case 標籤可以放在 if-else 語句中。

示例

#include <stdio.h>
main() {
   int x = 2, y = 2;
   switch(x) {
      case 1:
         ;
         if (y==5) {
            case 2:
               printf("Hello World");
         }
         else case 3: {
            //case 3 block
         }
   }
}

輸出

Hello World
  • array[index] 可以寫成 index[array]。原因是陣列元素是使用指標算術訪問的。array[5] 的值為 *(array + 5)。如果以相反的順序(例如 5[array])編寫,那麼它也與 *(5 + array) 相同。

示例

#include <stdio.h>
main() {
   int array[10] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 110};
   printf("array[5]: %d
", array[5]);    printf("5[array]: %d
", 5[array]); }

輸出

array[5]: 66
5[array]: 66
  • 我們可以在方括號 [,] 的位置使用 <: , :>,在花括號 {,} 的位置使用 <%, %>。

示例

#include <stdio.h>
main() <%
int array<:10:> = <%11, 22, 33, 44, 55, 66, 77, 88, 99, 110%>;
printf("array[5]: %d
", array<:5:>); %>

輸出

array[5]: 66
  • 我們可以在某些奇怪的地方使用 #include。我們以一個檔案 abc.txt 為例,其中包含一行“The Quick Brown Fox Jumps Over The Lazy Dog”。如果我們在 printf 語句後包含該檔案,則我們可以列印該檔案內容。

示例

#include <stdio.h>
main() {
   printf
   #include "abc.txt" ;
}

輸出

The Quick Brown Fox Jumps Over The Lazy Dog
  • 我們可以使用 %*d 忽略 scanf() 中的輸入。

示例

#include <stdio.h>
main() {
   int x;
   printf("Enter two numbers: ");
      scanf("%*d%d", &x);
   printf("The first one is not taken, the x is: %d", x);

}

輸出

Enter two numbers: 56 69
The first one is not taken, the x is: 69

更新於:2019-07-30

332 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.