A
Anupam
Hi,
This was asked on our school newsgroup by a friend of mine.
He gave the following code and said that it did not print out
the elements of the array. He asked for an explanation for this
behaviour. I whittled this down a bit but I am unable to pin it
to a reference from the standard which I would like to have given
when explaining it.
Ok here goes.
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main(void)
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
/* TOTAL_ELEMENTS is actually getting evaluated to an unsigned
int. Since sizeof returns size_t which is unsigned int.
I assume that this is the problem since the problem was reproduced
if I used this line instead:
for(d=-1;d <= ((unsigned int)7-2);d++)
This for some reason is either implementation defined behaviour
or undefined behaviour since I got two separate outputs from two
compilers.. one being Turbo C and one the VC compiler.
In one case it is not printing out any element of the array
since the LHS is forcing itself up into unsigned int ...
In the other case the unsigned int is coverted into an int, thus
there are no problems.
*/
printf("%d\n",array[d+1]);
return EXIT_SUCCESS;
}
Would like to hear your comments regarding the above explanation.
Regards,
Anupam
This was asked on our school newsgroup by a friend of mine.
He gave the following code and said that it did not print out
the elements of the array. He asked for an explanation for this
behaviour. I whittled this down a bit but I am unable to pin it
to a reference from the standard which I would like to have given
when explaining it.
Ok here goes.
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main(void)
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
/* TOTAL_ELEMENTS is actually getting evaluated to an unsigned
int. Since sizeof returns size_t which is unsigned int.
I assume that this is the problem since the problem was reproduced
if I used this line instead:
for(d=-1;d <= ((unsigned int)7-2);d++)
This for some reason is either implementation defined behaviour
or undefined behaviour since I got two separate outputs from two
compilers.. one being Turbo C and one the VC compiler.
In one case it is not printing out any element of the array
since the LHS is forcing itself up into unsigned int ...
In the other case the unsigned int is coverted into an int, thus
there are no problems.
*/
printf("%d\n",array[d+1]);
return EXIT_SUCCESS;
}
Would like to hear your comments regarding the above explanation.
Regards,
Anupam