syk435
syk435

Reputation: 308

What exactly is the difference between x++ and x+1?

I've been thinking about this in terms of incrementing a pointer, but i guess in general now I don't know the semantic difference between these two operations/ operators. For example, my professor said that if you have int a[10] you can't say a++ to point at the next element, but I know from experience that a+1 does work. I asked why and he said something like "a++ is an action and a+1 is an expression". What did he mean by it's an "action"? If anyone could tell me more about this and the inherent difference between the two operations I'd greatly appreciate it. Thank you.

Upvotes: 5

Views: 18262

Answers (6)

Shoe
Shoe

Reputation: 76240

x++ and ++x

The increment operator x++ will modify and usually returns a copy of the old x. On a side note the prefixed ++x will still modify x but will returns the new x.

In fact x++ can be seen as a sort of:

{
    int temp = x; 
    x = x + 1; 
    return temp;
}

while ++x will be more like:

{
    x = x + 1;
    return x;
}

x + 1

The x+1 operation will just return the value of the expression and will not modify x. And it can be seen as:

{
    return (x + 1);
}

Upvotes: 13

teppic
teppic

Reputation: 8195

Every expression returns a result (unless it's void).

x + 1 returns the value of x + 1.

x++ returns the value of x, and as a side effect the value of x is incremented at some point, not necessarily immediately.

This means you can have:

x = x + 1;

but this is illegal:

x = x++;

Upvotes: 0

user2187876
user2187876

Reputation: 31

a++ will translate to a=a+1 which is an action (due to the contained assignment operation) a+1 is just an expression which refers to a+1 (either in pointer terms or in terms of a number depending upon a's type)

Upvotes: 3

user123
user123

Reputation: 9071

x++ is a const expression that modifies the value of x (It increases it by 1). If you reference x++, the expression will return the value of x before it is incremented.

The expression ++x will return the value of x after it is incremented.

x + 1 however, is an expression that represents the value of x + 1. It does not modify the value of x.

Upvotes: 3

Ben313
Ben313

Reputation: 1668

x++ is equivalent to x = x + 1. It is an action in that it is actually changing the value of x.

Upvotes: 0

Doug Currie
Doug Currie

Reputation: 41180

x++ is an action in the sense that it changes x

x+1 does not change x

Upvotes: 6

Related Questions