Joe Wright wrote:
Alex said:
char* pch [120];
// Should we check
// if (((size_t) pch & 3) == 0)
// before the following statement ?
int* pint = (int*) pch;
That would be both a declaration and an object definition,
but the above line of code, is not a statement.
What is it, then.
pch is not a char pointer. It is an array [120] of pointers
to char.
And, prior to being operated on by each cast operator,
the expression (pch),
is implicitly converted to type (char **).
I think Alex is depending on some intimate knowledge
of a specific C implementation.
I think it would be better if he actually told us what he is
trying to do. I can't see any case where his exact code would
make sense.
According to the rules of C, whether or not
int* pint = (int*) pch;
will work right, depends on size and alignment issues.
Amongst other things. Regretfully, Alex cross-posted, and the
rules for C and for C++ here are subtly different. In C, if pch
is not correctly aligned for the target type, the behavior is
undefined; in C++ the results are unspecified, even if the
alignment is correct. But those are really subtilities: in both
cases, it's something you don't do except in very low level,
machine dependent code (in which case, of course, your program
depends on what the compiler does with it).
It *cannot* be construed from the C standard, that
if (((size_t) pch & 3) == 0)
is sufficient to check for those size and alignment issues.
It may not even be legal (requiring a compiler diagnostic in
C++, and resulting in undefined behavior in C). According to
the relevant standards, the conversion is only legal if size_t
is large enough to hold the pointer type (and I've used systems
where size_t was 16 bits, and char* 32, or where size_t was 32
bits, and char* 48).
Even when it is legal, the results of the conversion are
implementation defined. The C++ standard adds the note: "it is
intended to be unsurprising to those who know the addressing
structure of the underlying machine", but that's just a note,
and non-normative. And it really doesn't mean much anyway.
(FWIW: the low order bits of a byte pointer on a PDP-10 where
somewhere in the upper half of the word, which means that his
test wouldn't look at them anyway.)
In practice, of course, as others have already pointed out:
what's he going to do if the test fails (as it almost certainly
will under some conditions)?