Reputation: 61
Many people know the following example to find out whether a system is little endian or big endian:
#include <stdio.h>
int main()
{
unsigned int i = 1;
char *c = (char*)&i;
if (*c)
printf("Little-endian");
else
printf("Big-endian");
getchar();
return 0;
}
However, I would like to know whether the following piece of code is also still valid and functional:
#include <stdio.h>
int main()
{
unsigned int i = 1;
char *c = &i;
if (*c)
printf("Little-endian");
else
printf("Big-endian");
getchar();
return 0;
}
I want to ask whether the address of operator, &, works the same on both big-endian and little-endian systems. Will it in both cases point to the lowest addressed byte of the object when a pointer to an object is converted to a pointer to a character type?
My worry is the following. Suppose that you do not do the type conversion as above and also suppose a big-endian system returns you the highest bit address (basically where the int starts), then this piece of code will still print "Little-endian" although you are really dealing with a big-endian system.
Any comment on this would be really helpful. Thank you in advance :D.
Upvotes: 1
Views: 192
Reputation: 223484
The assignment char *c = &i;
violates the constraints in C 2018 6.5.16.1 1. That paragraph says “One of the following shall hold,” and the closest match in the list of options is:
char *
and int *
are not compatible, so the assignment fails the constraints.
That said, if the compiler did accept this statement (which it may, since the C standard permits extensions) and converts the pointer on the right to the type on the left (as assignments should), the result should be a pointer to the lowest addressed byte of the object, regardless of endianness. This is normal for pointer conversions per C 2018 6.3.2.3 7:
… When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object.
Upvotes: 4
Reputation: 6405
The second example will give you a compiler warning that the assignment is invalid without a casting. If you ignore the warning, you might get the same result or not, as always when trying undefined behavior.
Upvotes: 0