John Reye <> wrote:
> 1)
> a[i] = i++;
> http://c-faq.com/expr/evalorder1.html
> So this attempt at optimisation is wrong:
> int i;
> int a[10];
> for (i = 0; i < sizeof(a); )
> a[i] = i++; /* set a to {1, 2, 3, ...} */
> Correctly optimized, it should be:
> for (i = 0; i < sizeof(a); )
> i = a[i] = i+1; /* set a to {1, 2, 3, ...} */
I don
't know what this has to do with "optimiation" but, tes, the
second version is more correct. But there's still a problemL
you use of sizeif(a) as the value for the end of the loop. But
sizeof(a) is the number of bytes in that array, not the number
of elements (and these are typically, except for char arrays,
different). Use instead "sizeof a / sizeof *a" (and make sure
that 'a' is an array and not merely a pointer).
> 2)
> int i;
> char b[10];
> (int *)b = i;
> Alignment problem. There is not guarantee that b is so aligned, that
> it's address satisfies alignment-requirements, which an int-pointer
> would need (such as even address, or maby "address divisible by 4", or
> whatever it happens to be)
True. If, for some reasons, you must do that use memcpy().
> 3)
> struct
> {
> char a;
> int b;
> } mystruct;
> // set byte at lowest address within b to 0x12;
> char *p = &mystruct;
> p[1] = 0x12;
> Bug: struct padding was forgotten. There will probably be some padding
> between a and b, so that b is aligned for good memory-access.
> Rather use:
> *((char *)&mystruct.b) = 0x12;
Correct but also don't do that unless you have very good reasons
- why would you set just one of the bytes of an int? Depending
on the endianness etc. of your machine the result when the 'b'
member then is used as an int will be quite different.
> Or:
> struct
> {
> char a;
> union {
> int b;
> char c;
> };
> } mystruct;
> mystruct.c = 0x12
> Would this union work on every platform??
Yes. But the you won't be able to use the 'b' element of
the union since reading a different member than has been
set the last time round also invokes undefined behavior.
> Which undefined behaviour (or other bugs) do you think is interesting
> to know about?
All of them

There's a complete list at the end of the C
standard (at least in C89, see A.6.2, and C99, see Annex J2).
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de