我已經在gcc上測試過這個程序,它的答案是1.我怎麼找不到原因?
main()
{
int c = 5;
printf("%d", main||c);
}
答案:它顯示上的gcc編譯器(開發的C++)主函數如何作爲主函數寫入時實際表現如下|| integer
main()
{
int c = 5;
printf("%d", main||c);
}
答案:它顯示上的gcc編譯器(開發的C++)主函數如何作爲主函數寫入時實際表現如下|| integer
這是一個邏輯OR
操作。如果main
中的至少一個不是NULL
指針或c
非零,則其評估爲1;否則,它將產生0.因爲main()
是一個現有的函數,所以它的指針不是NULL
,並且5
也不爲零,因此此代碼將打印1
。
@Atiq「但我們可以使用沒有括號的函數嗎」 - 是的,你可以,它意味着一個指向該函數的指針。 「變量分隔」是什麼意思? – 2013-04-07 16:32:48
當它自己出現沒有括號時,main
是pointer to function(實際上,地址爲main()
)。
因此
main || c
相當於
(main != NULL) || (c != 0)
總是計算結果爲真(即1
)。
main||c
是合乎邏輯的OR
它將測試main
非空的函數指針和c
,它有一些非零值。由於它們都不是zero
或NULL
,它總是會打印1
,因爲這是邏輯OR
的輸出。
你應該使用gcc的-Wall
選項來編譯它(幾乎可以獲得所有的警告,-Wextra
你會得到更多的警告)。隨着gcc-4.8
我越來越
% gcc-4.8 -Wall atiq.c -o atiq
atiq.c:1:1: warning: return type defaults to 'int' [-Wreturn-type]
main()
^
atiq.c: In function 'main':
atiq.c:4:1: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
printf("%d", main||c);
^
atiq.c:4:1: warning: incompatible implicit declaration of built-in function 'printf' [enabled by default]
atiq.c:4:14: warning: the address of 'main' will always evaluate as 'true' [-Waddress]
printf("%d", main||c);
^
atiq.c:5:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
我想警告是很清楚。並且您看到main
始終爲非空地址,因此main||c
始終爲真。
您的代碼缺少#include <stdio.h>
什麼是你期望的輸出是什麼? – NPE 2013-04-07 16:29:16