Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

operators

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.

like image 929
syk435 Avatar asked Mar 19 '13 18:03

syk435


People also ask

What is difference between x ++ and X 1?

Difference between x++ and x= x+1 in Java programmingx++ automatically handles the type casting where as x= x + 1 needs typecasting in case of x is not an int variable. See the example below.

What is x++ and x 1 in c?

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 .

Are x += 1 and x ++ the same?

You probably learned that x++ is the same as x = x+1 .

How does X ++ or differ from ++ x explain with suitable example?

x++ and ++x both are increment operator which are used to increase the value of a variable by 1, there is a very slight difference between two. In x++ the value of variable is printed first then it is incremented whereas in ++x the value is incremented first and then it is displayed. hope u understood it.


1 Answers

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);
}
like image 58
Shoe Avatar answered Oct 20 '22 06:10

Shoe