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,都输出。