My first programming teacher had a saying. "You're scratching your left ear with your right hand."
This is like scratching your left ear with your right knee.
1. Why does d start at -1?
2. Why is it array indexed with d+1 (although it actually says n+1, which means the program doesn't even compile).
3. Why is the for condition <=?
4. Why "d<=(TOTAL_ELEMENT-2)"?
Your question is valid and a tough one but I don't know the answer. I suspect it has to do with C macro substitution gone wrong.
1 2 3 4 5 6
int total = TOTAL_ELEMENT;
for(d=-1;d<=(total-2);d++)
{
printf("%d \n",array[d+1]);
}
Above works. So I suspect when we put d<=(TOTAL_ELEMENT-2) it is not working at all. When I substitute inside d<=((sizeof(array)/sizeof(array[0]))-2) still cannot. Then I remove -2 like d <= (sizeof(array)/sizeof(array[0]) also cannot.
I am suspecting the macro TOTAL_ELEMENT is not evaluated inside the for loop syntax which is strange. Hmmmm.... hope to see expert C++ advice on this problem though.
No expert here. Just noticed the #define preceeds the declaration of array so the sizeof() functions may give garbage. I'm surprised it will build since array doesn't exist yet where the #define is made. Try reversing these lines.
There seem to be 2 kinds of macro. Object-like and function-like. I presume function-like will attempt to execute and get the result whereas object-like just do plain text substitution ?
warning: comparison between signed and unsigned integer expressions
It refers to this -> d<=(TOTAL_ELEMENT-2);
What happens is that d is 'converted' to an unsigned int before the comparison. When you take -1 and see it as an unsigned int, it's quite big... That's why the loop body never executes. This will work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<cstdio>
#define TOTAL_ELEMENT (sizeof(array) / sizeof(array[0]))
int array[]={1,2,3,4,5,6,7};
int main()
{
int d;
for(d=-1;d<=signed(TOTAL_ELEMENT-2);d++)
{
printf("%d\n",array[d+1]);
}
return 0;
}
Above says "A sizeof expression evaluates to an unsigned value equal to the size in bytes of the "argument" datatype, variable, or expression (with datatypes, sizeof evaluates to the size of the datatype; for variables and expressions it evaluates to the size of the type of the variable or expression)."
Now the mystery is solved. m4ster r0shi post is correct. This is tricky question.