Are there any problems with the "sequence" with expressions such as "int a = 4, * ptr = & a;" or "x + = 4, y = x * 2;"?

My understanding of the whole point of the sequence of things is basic. All I have is a crude intuitive idea: "When a sequence point occurs, we can be sure that all the side effects of previous evaluations are complete." I also read that in expressions like printf("%d",a++,++a,a++) , the behavior is undefined, since the comma does not indicate a sequence point, while the semicolon is executed. Therefore, instead of speculating and going on intuition, I feel that a very strict and convincing answer to this will help me a lot.

So in C:

The following statements exist:
 int a=4,*ptr=&a; //Statement 1 x+=4,y=x*2; //Statement 2 (Assume x and y are integer variables) 

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

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

and

 x+=4; y=x*2; 

Change My understanding of the comma operator tells me that these statements are safe. But after reading about the points in the sequence and like something like printf("%d",a++,++a,a++) is undefined, I have other thoughts.

+6
source share
2 answers

The comma separating the function arguments in the function call is not a comma operator — it is just punctuation, which can be written in the same way as the comma operator. There is no point in the sequence between evaluating the various arguments of the function, so you get UB in this case.

On the other hand, in your expression:

 x+=4,y=x*2; 

here the comma is a comma operator that enters a point in the sequence; there is no UB.

In a declaration, a comma between declarators is also not a comma operator; however, the end of the complete declarator (a declarator that is not part of another declarator) introduces a point in the sequence, so a declaration like:

 int a = 2, b = a + 1; 

not UB.

+12
source

There is no UB.
According to the C99 standard:

C. Appendix C (informative): Sequential points
# 1 Below are the sequence points described in 5.1.2.3:
- function call after evaluating the arguments (6.5.2.2).
- end of the first operand following operators: logical AND && (6.5.13); logical OR || (6.5.14); conditional? (6.5.15); comma, (6.5.17).

Thus, when calling the function, there is no comma operator. Despite the presence of a comma.

+3
source

Source: https://habr.com/ru/post/943814/


All Articles