Thursday, November 27, 2008

C/C++ puzzler #2 - Is it typo ?

Ok, here is next C/C++ specific puzzler. Puzzler here is to guess, what will be result of program ?

  1. It won't compile

  2. It will compile, but it will segfault when we try to run it

  3. It will run and print 4 times 30

  4. Anything else you can think of



Highlight text bellow code to find out correct answer.


/* compile with cc -g -o test_typedef_sizeof test_typedef_sizeof.c */
#include <stdio.h>
#include <string.h>

typedef char name_t[30];

void fn(name_t value)
{
printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(value));
}

int main (void)
{
name_t aa;

printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(aa));

fn(aa);
return 0;
}



I'll just show you program output:

30
30
30
4

Is it not, what you have expected ? Fine, let's walk the program together. On entry to main() program prints sizeof(user defined type name_t), which has length of 30 chars. Next it'll print sizeof(instance of name_t) which again is 30 chars long. Then it calls function fn(instance of name_t), In fn() it prints sizeof(user defined type name_t) which is again 30 bytes. But when it tries to print sizeof(value) it prints 4, because arrays are passed as reference to first element in C/C++. And the sizeof(pointer) is 4 respectively 8 for 64 bit system.

Java EE factsheets

Stefan Jäger recently posted bunch of Java EE fact-sheets on his blog. Stefan created fact-sheets for: SF and SL session beans, MDB's and JMS, Transactions and security, and finally JPA. Very nice, and available as PDF downloads.