Intersting C examples

From C Puzzles


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.

 #include<stdio.h>

  #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

  int array[] = {23,34,12,17,204,99,16};

  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就不会出现这样的情况。

延伸:在有符号和无符号的数比较时,有符号的数将先转化成无符号的数然后再比较。有一篇博文写的比较详细:
http://www.360doc.com/content/14/0320/17/1317564_362209181.shtml


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 :-) ?

#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  变量名中含-


The following program doesn't "seem" to print "hello-out". (Try executing it)

 #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是无缓冲的,会直接输 出,举例来说就是printf(stdout, "xxxx") 和 printf(stdout, "xxxx\n"),前者会憋住,直到遇到新行才会 一起输出。而printf(stderr, "xxxxx"),不管有么有\n,都输出。



你可能感兴趣的:(Intersting C examples)