English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

What is the difference of y++ and y=y+1?

2007-03-15 02:34:21 · 5 answers · asked by chan-chan 3 in Computers & Internet Programming & Design

5 answers

The difference is one is cryptic and one is clear. The actual purpose of y++ is that it can be used as both a value *and* an expression.

This is what I mean:

int y = 5;
int x = y++; // after this statement, x is 5 and y is 6

y = 5;
x = ++y; // after this statement, x is 6 because ++y increments y first and then uses that resulting value

This syntax is not required at all. It is a programmer's convenience.

2007-03-15 02:53:52 · answer #1 · answered by Anonymous · 0 0

They do more ore less the same, increment y by 1. There are more variations, depending on your programming language. For example, PHP has $y = $y + 1, $y += 1, $y++ and ++$y.

The difference is that y = y + 1 is an assignment, and y++ an increment. You can use increments in expressions, like x = y++ and x = ++y. This way you can do two things in one line of code.

The difference between y++ (post increment) and ++y (pre increment) is the order in which values get assigned.

With the post increment x = y++ first x will be assigned the value of y, and then y will be incremented.

With the pre increment x = ++y first y will be incremented, and then x will be assigned the value of y.

For example, let's say y = 1. If you do this:

x = y++
z = ++y

Then the results are:

x = 1, y = 3 and z = 3

2007-03-15 10:07:36 · answer #2 · answered by GodBuster 5 · 0 0

Short answer: 2 characters.

Longer answer: It's called syntactic sugar. Some languages allow you to do stuff like this. Java,C++,C# etc...


The end result is y is incremented by 1. It really helps out when your variable name is something more along the lines of...

someStupidlyLongVariableNameThatYouReallyDontWantToHaveToTypeSoMuch


someStupidlyLongVariableNameThatYouReallyDontWantToHaveToTypeSoMuch++

OR

someStupidlyLongVariableNameThatYouReallyDontWantToHaveToTypeSoMuch = someStupidlyLongVariableNameThatYouReallyDontWantToHaveToTypeSoMuch + 1

2007-03-15 11:03:01 · answer #3 · answered by O20Sublime 1 · 0 0

No difference at all except in the writing method

2007-03-15 09:42:52 · answer #4 · answered by ramy e 2 · 0 0

Take a look at this web page for details

2007-03-15 09:44:44 · answer #5 · answered by AnalProgrammer 7 · 0 0

fedest.com, questions and answers