From C Puzzleshtml
The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.spa
#include<stdio.h>code #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))htm int array[] = {23,34,12,17,204,99,16};element int main(){ int d; for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) printf("%d\n",array[d+1]); return 0; } |
d賦值爲-1, 與宏NUM-2(值爲5)相比較,這時d轉化爲無符號的數,所以條件爲假,for循環未進入,若將NUM換爲 const int就不會出現這樣的狀況。get
延伸:在有符號和無符號的數比較時,有符號的數將先轉化成無符號的數而後再比較。有一篇博文寫的比較詳細:
http://www.360doc.com/content/14/0320/17/1317564_362209181.shtmlit
I thought the following program was a perfect C program. But on compiling, I found a silly mistake. Can you find it out (without compiling the program :-) ?io
#include<stdio.h> void OS_Solaris_print() { printf("Solaris - Sun Microsystems\n"); } void OS_Windows_print() { printf("Windows - Microsoft\n"); } void OS_HP-UX_print() { printf("HP-UX - Hewlett Packard\n"); } int main() { int num; printf("Enter the number (1-3):\n"); scanf("%d",&num); switch(num) { case 1: OS_Solaris_print(); break; case 2: OS_Windows_print(); break; case 3: OS_HP-UX_print(); break; default: printf("Hmm! only 1-3 :-)\n"); break; } return 0; }
。。。。。。居然只是變量名錯了,OS_HP-UX_print 變量名中含-for循環
The following program doesn't "seem" to print "hello-out". (Try executing it)table
#include <stdio.h> #include <unistd.h> int main() {while(1) { fprintf(stdout,"hello-out"); fprintf(stderr,"hello-err"); sleep(1); } return 0; } |
輸出結果是:hello-errhello-out,stdout, stder分別表示標準輸出,標準錯誤,默認都是將信息輸出到終端上,在默認狀況下,stdout是行緩衝的,他的輸出會放在一個buffer裏面,只有到換行的時候,纔會輸出到屏幕。而stderr是無緩衝的,會直接輸 出,舉例來講就是fprintf(stdout, "xxxx") 和 fprintf(stdout, "xxxx\n"),前者會憋住,直到遇到新行纔會 一塊兒輸出。而fprintf(stderr, "xxxxx"),無論有麼有\n,都輸出。