1Process returned 0 (0x0) ? execution time : 0.041 sPress any key to continue.end
分析
這個需要查看文檔了:continue 會到循環的哪個地方繼續運行。
于是我查看了官方文檔
For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.
什么意思呢?
for 循環遇到 continue 會執行for 小括號內的第三個語句。
while 和 do...while 則會跳到循環判斷的地方。
宏的展開
問題
大多數情況下,我們的宏定義常常是嵌套的。
這就涉及到展開宏定義的順序了。
下面來看看其中一個問題。
代碼
#include <stdio.h>#define f(a,b) a##b#define g(a) ? #a#define h(a) g(a)int main() {printf("%s ",h(f(1,2)));printf("%s ",g(f(1,2)));return 0;}
輸出
12f(1,2)Process returned 0 (0x0) ? execution time : 0.041 sPress any key to continue.end
分析
這個問題又需要查看文檔了:Macro 是怎么展開的。
于是我查看了官方文檔
Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.
簡單的說就是 宏會掃描一遍,把可以展開的展開,展開一次后會再掃描一次看又沒有可以展開的宏。
下面我們模擬一下這個過程就可以明白了。
代碼
#include <stdio.h>int main() {int i=43;printf("%d ",printf("%d",printf("%d",i)));return 0;}
輸出
4321Process returned 0 (0x0) ? execution time : 0.035 sPress any key to continue.end
分析
printf 的返回值是輸出的字符的長度。
所以第一個輸出 43 返回2.
第二個輸出 2 返回 1. 第三個輸出1. 于是輸出的就是 4321 了。
數組參數
問題
對于函數傳參為數組時,你知道到底傳的是什么嗎?
代碼
#include<stdio.h>#define SIZE 10void size(int arr[SIZE][SIZE]) {printf("%d %d ",sizeof(arr),sizeof(arr[0]));}int main() {int arr[SIZE][SIZE];size(arr);return 0;}
輸出
4 40Process returned 0 (0x0) ? execution time : 0.039 sPress any key to continue.end
分析
對于第二個輸出,應該是 40 這個大家都沒有什么疑問的。
但是第一個是幾呢?
你是不是想著是 400 呢?
答案是 4.
這是因為對于數組參數。第一級永遠是指針形式。
也就是說數組參數永遠是指針數組。
所以第一級永遠是指針,而剩下的級數由于需要使用 [] 運算符, 所以不能是指針。
sizeof 的參數
問題
當我們有時候想讓代碼簡潔點的時候,會把運算壓縮到一起。
但是在 sizeof 中就要小心了。
代碼
#include <stdio.h>int main() {int i;i = 10;printf("i : %d ",i);printf("sizeof(i++) is: %d ",sizeof(i++));printf("i : %d ",i);return 0;}
輸出
i : 10sizeof(i++) is: 4i : 10Process returned 0 (0x0) ? execution time : 0.039 sPress any key to continue.end
分析
你猜第二個i的輸出時什么呢?
11 嗎?
恭喜你,猜錯了。
這個還需要查看文檔了。
首先我的印象中 sizeof 是個宏,在編譯器運算的。
The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type.
文檔上說 sizeof 是一個關鍵字,但是在編譯器運算。