A friend gave me a riddle:
#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]);
getchar();
return 0;
}
The above code is supposed to print all the array elements, what is the problem in the code (the output is nothing)? I think the loop doesn't iterate even once?
I found out that the following code does work:
#include<stdio.h>
#define TOTAL_ELEMENTS ((sizeof(array) / sizeof(array[0])))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
int x = (TOTAL_ELEMENTS-2);
for(d=-1;d <= x;d++)
printf("%d\n",array[d+1]);
getchar();
return 0;
}
I have a theory that it's something to do with the macro, but I can't put my finger on the problem.
In this C programming puzzle you need to merge two numbers. You cannot use any arithmetic, string or other functions. Optimum solution to this C programming puzzle is to use the Token-pasting operator define. Define a macros using this ## token-pasting operator gives you the merged value.
The problem is that (TOTAL_ELEMENTS-2)
is an unsigned value. When you make the comparison d <= (TOTAL_ELEMENTS-2)
, both values are converted to unsigned values, and the result is false.
In your second example, x
is signed so there is no problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With