Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there "sequence-point" issues with statements like "int a=4,*ptr=&a;" or "x+=4,y=x*2;"?

My understanding of the whole sequence points thing is basic. All I have is some crude intuitive idea that "once a sequence point is encountered, we can be sure all side effects of previous evaluations are complete". I also read that in statements like printf("%d",a++,++a,a++) the behavior is undefined as a comma doesn't signify a sequence point while a semi-colon does. So instead of making guesses and going by intuition, I feel a very rigorous and conclusive answer to this will help me a lot.

So are the following kind of statements safe & certain in C:

int a=4,*ptr=&a;  //Statement 1

x+=4,y=x*2;  //Statement 2  (Assume x and y are integer variables)

If yes, how? Especially in the second case, if a comma is not a sequence point, how can we be sure x has been incremented by 4 before we use it in the assignment y=x*2? And for the first statement, how can I be sure a has been initialized and allocated memory before I assign its address to ptr? Should I play safe and use the following for the above:

int a=4,*ptr;
ptr=&a;

and

x+=4;
y=x*2;

Edit My understanding of the comma operator tells me that those statements are safe. But after reading about sequence points and how something like printf("%d",a++,++a,a++) is undefined, I am having second thoughts.

like image 321
Rüppell's Vulture Avatar asked Apr 28 '13 12:04

Rüppell's Vulture


2 Answers

The comma that separates function arguments in a function call is not a comma operator - it's just punctuation that happens to be spelled in the same way as the comma operator. There's no sequence point between the evaluation of different function arguments, so that's why you get UB in that case.

On the other hand, in your expression:

x+=4,y=x*2;

the comma here is a comma operator, which introduces a sequence point; there's no UB.

In a declaration, the comma between declarators is also not a comma operator; however, the end of a full declarator (a declarator not part of another declarator) does introduce a sequence point, so a declaration like:

int a = 2, b = a + 1;

is not UB.

like image 169
caf Avatar answered Oct 03 '22 02:10

caf


There is no UB here.
As per C99 standard:

C. Annex C (informative): Sequence points
#1 The following are the sequence points described in 5.1.2.3:
-- The call to a function, after the arguments have been evaluated (6.5.2.2).
-- The end of the first operand of the following operators: logical AND && (6.5.13); logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).

Thus there is no comma operator involved upon function call. Despite presence of comma.

like image 25
alexrider Avatar answered Oct 03 '22 03:10

alexrider