C puzzle – 1

Today it’s a C puzzle day – I got foxed at one of the questions my friend threw at me so decided to hunt up and practice some C puzzles. At worst, it will prepare me for interviews 🙂

This one is from GowriKumar’s website.

#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++)
return 0;


The usual, what’s wrong. This was straightforward, and involves understanding type promotion – something I mentioned before. The reason I put it here is: I read somewhere that I can make the preprocessor create the type I wanted – by doing something like this.

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

This is supposed to make the compiler treat it as an unsigned long. So I wanted to find out what I should use for signed int. Well, I haven’t figured that out and UL didn’t work either – so I finally cast it as usual:

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

Bleargh – someone tell me why UL doesn’t work. It’s clearly mentioned here.

I’m using gcc 4.1.2.


2 thoughts on “C puzzle – 1

  1. Because UL only works as part of an integer literal. Like 42UL.

    Just use an explicit cast to convert the type:
    #define TOTAL_ELEMENTS ((int)((sizeof array)/sizeof(array[0])))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s