Pointer Arithmetic Problem

B

Ben Bacarisse

arnuld said:
Um, not quite. You can certainly read and then modify the value of an
object with an expression; for example, "i = i + 1;" is ok.

That I know, because there is stupidity revolving here like i = i++ + 1.

Huh? Do you mean that "i = i + 1;" and "a = i;" are two different
expressions? Yes, they are (actually two different expression
statements). What's your point?



point is: If we put both of them in one expression, then we will stilll
have well-defined behavior, so why you used 2 expressions:

printf("values are: %d and %d\n", i = i + 1, a = i);

its not UB.


Yes it is. If you find the legalese hard, I find the following
useful: if you can find two (or more) valid orders of execution that
give different results then the code is UB. I am not sure that this
always works but it seems, in practise, to be pretty useful.

In your example, the result depends on the unspecified order of
evaluation of function arguments so by my rule of thumb it is UB. The
real reason is because it violates the quoted clause in the standard,
but this rule helps to see why.
 
R

Richard Tobin

Ben Bacarisse said:
Yes it is. If you find the legalese hard, I find the following
useful: if you can find two (or more) valid orders of execution that
give different results then the code is UB. I am not sure that this
always works but it seems, in practise, to be pretty useful.

Not only is that a good rule of thumb, but it explains *why* it's
undefined behaviour: different compilers may choose different orders,
or perhaps even interleave execution of the expressions.

-- Richard
 
K

Keith Thompson

arnuld said:
That I know, because there is stupidity revolving here like i = i++ + 1.

Good, but the rule as you stated it above implies that "i = i + 1;" is
undefined.
Huh? Do you mean that "i = i + 1;" and "a = i;" are two different
expressions? Yes, they are (actually two different expression
statements). What's your point?


point is: If we put both of them in one expression, then we will stilll
have well-defined behavior, so why you used 2 expressions:

printf("values are: %d and %d\n", i = i + 1, a = i);

its not UB.


Yes, it is. But even if it weren't, using two examples is clearer
than shoving the examples together into a single more complicated
expression.

[...]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

pointer to pointer 7
using a pointer vs array 12
Find the size of an array 21
Selection-Sort in C 35
Binary Search in C 7
strtoul() behavior 39
insertion sort in C 14
strcpy - my implementation 64

Members online

No members online now.

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top