I came across a code to find the endianess, wherein a union containing an integer and character is initialized and the integer is set to 1. Now, say that this is big endian, the MSB is going to be zero. Now what would be the value of the character? Would it be '0' or some other format ?
This made me thinking: if there is a C-style cast like in "*(unsigned char *)&a", how can it be known what exactly in an arbitrary expression will be tried to cast? Do you have any real-life ambiguities in mind?
how can it be known what exactly in an arbitrary expression will be tried to cast? Do you have any real-life ambiguities in mind?
The first three times I read these sentences, I thought you were talking about the undefined behavior of the expression. C Casts have, like all other operators, precedence. If you know the precedence rules, you can unambiguously predict the order of evaluation.
Well it's down. If I look into [1], I see (type) and now I understand: it's all the same precedence, but associativity is right-to-left... I missed to see (type).
@helios: Yes thats another way to do it. But my doubt is how can you equate a dereferenced char pointer (even though it has been typecasted from int pointer) to 1. Shouldn't it be more like a character equivalent of the integer 1.
So my question essentially boils down to this: If i have say an int pointer and typecast it to say, a different pointer type, when i dereference it, will I still get an integer ?
But my doubt is how can you equate a dereferenced char pointer (even though it has been typecasted from int pointer) to 1. Shouldn't it be more like a character equivalent of the integer 1.
The only difference between char and int is that char is smaller. '1' just means "the integer value of type char that this machine understand as the character for the Arabic numeral '1'". In other words (assuming ASCII), '1' and char(49) are semantically identical.
If i have say an int pointer and typecast it to say, a different pointer type, when i dereference it, will I still get an integer ?
No. You'll get what the pointer type you casted to is supposed to be pointing to. If you casted to char *, you dereference into a char; if you casted to std::vector<std::list<std::basic_string<unsigned long long> > > *, you dereference into a std::vector<std::list<std::basic_string<unsigned long long> > >.
Of course, there's no telling what will happen if what was originally at that memory location and what you're casting to are incompatible. For example,
what I am trying to say is that the left hand side of the equation represents a char type and the right hand represents an integer type. That is where I am confused....