Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple preincrement operations on a variable in C++(C ?)

Why does the following compile in C++?

int phew = 53;
++++++++++phew ;

The same code fails in C, why?

like image 294
Jatin Avatar asked Sep 11 '10 07:09

Jatin


People also ask

Which is the example of Preincrement operator?

Pre-Increment Operator in C Therefore, we can say that the pre-increment operator increases the value of the variable first and then use it in the expression. Syntax: b = ++a; For example, if the initial value of a were 5, then the value 6 would be assigned to b.

What is ++ i and i ++ in C?

++i : is pre-increment the other is post-increment. i++ : gets the element and then increments it. ++i : increments i and then returns the element. Example: int i = 0; printf("i: %d\n", i); printf("i++: %d\n", i++); printf("++i: %d\n", ++i); Output: i: 0 i++: 0 ++i: 2.

What is pre increment operator in C?

1) Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression.

What is the difference between Preincrement and Postincrement in C?

Pre-increment and Post-increment concept in C/C++?Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.


1 Answers

Note: The two defect reports DR#637 and DR#222 are important to understand the below's behavior rationale.


For explanation, in C++0x there are value computations and side effects. A side effect for example is an assigment, and a value computation is determining what an lvalue refers to or reading the value out of an lvalue. Note that C++0x has no sequence points anymore and this stuff is worded in terms of "sequenced before" / "sequenced after". And it is stated that

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

++v is equivalent to v += 1 which is equivalent to v = v + 1 (except that v is only evaluated once). This yields to ++ (v = v + 1) which I will write as inc = inc + 1, where inc refers to the lvalue result of v = v + 1.

In C++0x ++ ++v is not undefined behavior because for a = b the assignment is sequenced after value computation of b and a, but before value computation of the assignment expression. It follows that the asignment in v = v + 1 is sequenced before value computation of inc. And the assignment in inc = inc + 1 is sequenced after value computation of inc. In the end, both assignments will thus be sequenced, and there is no undefined behavior.

like image 175
Johannes Schaub - litb Avatar answered Oct 12 '22 06:10

Johannes Schaub - litb