Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between i++ and (i)++ in C

int i = 3;
int j = (i)++;

vs

int i = 3;
int j = i ++;

Is there a difference between how the above two cases are evaluated?

Is the first case equivalent to incrementing an rvalue or is it undefined behaviour?

like image 779
Polaris000 Avatar asked Feb 27 '19 15:02

Polaris000


People also ask

What is meaning of i ++ and ++ i?

answer i++ means post increment it means first the value of i is printed and then incremented. ++i means pre increment it means first value is incremented and then printed. i++ means post increment it means first the value of i is printed and then incremented.

What is the difference between i ++ and ++ i in C language?

What is the difference between ++i and i++ in C++? There is a big distinction between the suffix and prefix versions of ++. In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression.

Is i ++ the same as i i 1?

i = i+1 will increment the value of i, and then return the incremented value. i++ will increment the value of i, but return the original value that i held before being incremented.

What does ++ i mean in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent. i=5; i++; printf("%d",i);


2 Answers

i++ and (i)++ behave identically. C 2018 6.5.1 5 says:

A parenthesized expression is a primary expression. Its type and value are identical to those of the unparenthesized expression. It is an lvalue, a function designator, or a void expression if the unparenthesized expression is, respectively, an lvalue, a function designator, or a void expression.

The wording is the same in C 1999.

like image 74
Eric Postpischil Avatar answered Sep 20 '22 21:09

Eric Postpischil


In your simple example of i++ versus (i)++, there is no difference, as noted in Eric Postpischil's answer.

However, this difference is actually meaningful if you are dereferencing a pointer variable with the * operator and using the increment operator; there is a difference between *p++ and (*p)++.

The former statement dereferences the pointer and then increments the pointer itself; the latter statement dereferences the pointer then increments the dereferenced value.

like image 42
Govind Parmar Avatar answered Sep 17 '22 21:09

Govind Parmar