• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if conditions

 
Christoffer Blyerts
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

i get a bit confused sometimes of when a variable changes value or not in a if statement, for example:



x will be equal to 2 after this if statement.



In this case x will be equal to 3.


What are the rules for when the variable value gets changed or not within a if statement?


Thanks,

Christoffer

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64721
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has nothing at all to do with if statements, but with the operators you are using. ++ modifies its operand, + does not.
 
Guilherme Bazilio
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ++ sign is an increment operator (assignment). Used to modify (increment in one) the variable.


This snippet willl only modify the value of x variable after it's current value has been used. So in that if statement it will be evaluated to 2.


On the other hand, this one will modify (increment) the x variable before using it. Then it comes to be 3 in the if statement.

++ modifies the variable!

The + sign is just an arithmetic operator used to sum values and return the result. So x + 2 will be returned to any variable that wants to receive it.



After that code, y will be 2. In the if statement, the result of the sum is not assigned to any variable. The variable x keeps its value since we are not assigning any value to it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic