From: | Bart <bc@freeuk.com> |
Newsgroups: | comp.compilers |
Date: | Wed, 8 May 2019 01:14:29 +0100 |
Organization: | virginmedia.com |
References: | 19-04-021 19-04-023 19-04-037 19-04-039 19-04-042 19-04-044 19-04-047 19-05-004 19-05-006 19-05-016 19-05-020 19-05-024 19-05-025 19-05-028 19-05-029 19-05-034 19-05-045 |
Injection-Info: | gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="79199"; mail-complaints-to="abuse@iecc.com" |
Keywords: | standards, errors |
Posted-Date: | 07 May 2019 21:50:27 EDT |
In-Reply-To: | 19-05-045 |
Content-Language: | en-GB |
On 07/05/2019 10:04, David Brown wrote:
> Just for a laugh, try this code:
> #include <stdio.h>
>
> int main(void) {
> int i;
> int j;
> int *pi = &i;
> int *pj = &j;
> int sum = 0;
>
> printf("pi = %p, pj[-1] = %p\n", (void*) pi, (void*) &pj[-1]);
>
> for (i = 0; i < 11; i++) {
> if (i == 3) {
> pj[-1] = 5;
> }
> sum += i;
> }
> printf("Sum is %i\n", sum);
> }
This is the sort of code that /I/ would say has undefined behaviour. In
this case because pj points to a 1-element block, and you writing
outside that block.
With my C compiler, it shows '55', whatever order i and j are defined
in. That's because these int32 types are 64-bit aligned so have a 4-byte
gap between. I could get '48' if I changed the ints to 64 bits.
Translating to my language, and in the knowledge that the (64-bit) ints
there are assigned consecutively, and knowing that j follows i, then I
would expect a result of 48.
I expect it because that's what I coded, and my compilers tend to do
what I tell them in the language. If I wanted to do something underhand
like this for some genuine reason, and which would be well-defined
according to the provisos above, then I don't want to have to fight the
compiler to achieve it.
In that case, a compiler generating '55' would be undesirable.
Return to the
comp.compilers page.
Search the
comp.compilers archives again.