CBFalconer <> writes:
> James Kuyper wrote:
>>
> ... snip ...
>>
>> Appropriate use of sizeof is essential to writing portable code.
>> Example:
>> struct tm *t = malloc(sizeof *t);
>>
>> Would you care to suggest a more portable way of doing that which
>> doesn't involve use of the sizeof operator?
>>
>> Inappropriate use of sizeof can be dangerous, but then so can
>> inappropriate use of just about any other feature of C.
>
> Nit. I don't think that works. When sizeof is executed t has not
> yet been defined. I think it awaits the final semi.
Yes, it does work (though it took me a while to find the section in
the standard that proves it).
The object exists even before the declaration is reached. C99 6.2.4p4-5:
An object whose identifier is declared with no linkage and without
the storage-class specifier static has _automatic storage
duration_.
For such an object that does not have a variable length array
type, its lifetime extends from entry into the block with which it
is associated until execution of that block ends in any way.
But the real question is the scope. C99 6.2.1p7 says:
Structure, union, and enumeration tags have scope that begins just
after the appearance of the tag in a type specifier that declares
the tag. Each enumeration constant has scope that begins just
after the appearance of its defining enumerator in an enumerator
list. Any other identifier has scope that begins just after the
completion of its declarator.
In the declaration above:
struct tm *t = malloc(sizeof *t);
the declarator is ``*t'', the scope of t begins before the "=", and
the initializer is valid.
Incidentally, the fact that the lifetime of an automatic object starts
on entry to the block, before the declaration itself is reached, has
some interesting, though probably not very useful, consequences.
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i <= 1; i ++) {
int *foo_addr;
if (i == 1) {
printf("foo isn't visible yet, but its value is %d\n", *foo_addr);
}
int foo = 42;
if (i == 0) {
foo_addr = &foo;
}
}
return 0;
}
The output is:
foo isn't visible yet, but its value is 42
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"