Tuesday, August 02, 2005

C Quiz Part II -- Pointers into Arrays

Q. What is the output of this program?
int f(int b[][2]){ return ++b[0][0]; }
int g(int b[][2]){ return ++b,b[0][0]; }
int h(int b[][2]){ return (++b,b[0][0]); }
int i(int b[][2]){ return (1+b,b)[0][0]; }
main(){
    int a[][2]={101,201,301,401};
    printf("f=%d\n",f(a)); 
    printf("g=%d\n",g(a)); 
    printf("h=%d\n",h(a)); 
    printf("i=%d\n",i(a)); 
}    
Further reading.

C Quiz Part I

Q1. What is the output of this program:
main(){
  unsigned  int   nnn = -3;
  signed    int   ppp =  3;
  if( nnn >= ppp )
     printf("%d\n", nnn, ppp); // -3 >= 3
}  
Hint: Look up promotions.

Q2. What is the output of this program? and why

main(){
  int x=1,y=1;
  printf("s=%d\n",sizeof(printf("x=%d, y=%d\n",++x,++y)));
}  
Hint: Lookup Evaluation time of sizeof operator.

Q3. What about this?

main(){
  int x=1,y=1;
  printf("s=%d\n",printf("x=%d, y=%d\n",++x,++y));
}                                                                        

Q4. And this one

void main(){
  int x=1, y=100;
  x,y = y,x; // swap numbers, python style.
  printf("x=%d, y=%d\n",x,y);
}        

Q5. And this one:

void main(){
  int x=1, y=100;
  (x,y) = (y,x);
  printf("x=%d, y=%d\n",x,y); // swap number, perl style
}        
Put your answers as comments to this blog. Next check your answers with gcc, by compiling and running each of the programs. Windows users can download cygwin for gcc (the cygwin setup on windows is a breeze, and you get bash too). For explanations, see these two books: C Programming Language by Kernighan and Ritchie (aka KNR, K&R) C Reference Manual by Harbison and Steele Now try this excellent quiz by Pathak.