Alf P. Steinbach wrote:

> * Kai-Uwe Bux:

>> (E-Mail Removed) wrote:

>>

>>> The computer industry is changing, and 64-bit technology is the next,

>>> inevitable step.

>>> Look at sample.

>>>

>>> int main(int, const char **) {

>>> int a = -2;

>>> unsigned b = 1;

>>> int array[5] = { 1, 2, 3, 4, 5 };

>>> int *ptr = array + 3;

>>> ptr = ptr + (a + b); //Access violation on 64-bit platform

>>> printf("%i\n", *ptr);

>>> return 0;

>>> }

>>>

>>> Do you know why this code does not work on 64-bit system?

>>

>> For the same reason it does not work on 32 bit systems: the sum a+b is

>> subject to the conversion rules. Since b is of unsigned type, a is

>> converted to unsigned type [5/9]. This is undefined behavior for negative

>> values of a [5/5].

>

> I'd say "chapter and verse, please", except that seemingly you provided

> that -- except that AFAICS the references given don't correspond to

> anything in the standard.
They do:

[5/9]:

Many binary operators that expect operands of arithmetic or enumeration type

cause conversions and yield result types in a similar way. The purpose is

to yield a common type, which is also the type of the result. This pattern

is called the usual arithmetic conversions, which are defined as follows:

[...]

? Otherwise, if either operand is unsigned, the other shall be converted to

unsigned.

[5/5]:

If during the evaluation of an expression, the result is not mathematically

defined or not in the range of representable values for its type, the

behavior is undefined, unless such an expression is a constant expression

(5.19), in which case the program is ill-formed.

Probably the trickyness is that all of these come even before [5.1].

> Anyway, the signed->unsigned conversion is well-defined, §4.5/1 -> §4.7/2.
You are correct on that one, see my self-correction elsethread.

> (a + b) then yields -1 + 2^n, where n is the number of value

> representation bits in 'unsigned', and the rhs of the assignment ends up

> with an undefined value, which yields Undefined Behavior when assigned

> to 'ptr'.
True, I also realized that afterwards.

>> If it appears to work on your platform, then it was just

>> by coincidence.

>

> Yep.
Thanks

Kai-Uwe Bux