+ 2
Beginer Help
int a = 4; int b = 6; b = a++; Console.WriteLine(++b); Why is the output 5?
3 Respuestas
+ 2
RainbowColorSheep
•b = a++ is not equal to b = a + 1;
b = a++ means that the value of a will be assigned to b and then it will be incremented.
•++b means that b will be Incremented first then the value will be printed.
•b = a++;
-b = a = 4;
•Console.WriteLine(++b);
b = b + 1 = 4 + 1 = 5;
+ 2
This topic is about post-increment and pre-increment
Lets take the following as an example:
int a = 0;
int b = 1;
int c = a++; // returns 0
int d = ++a // returns 1
What happens during pre-increment, as int d as an example, the increment happens before returning the new int thus having 1 as the value of d.
Unlike post-increment, check the int c as an example, returns the value first before incrementing the int.
+ 2
1.Prefix(++a): Increments the variable's value and uses the new value in the expression.
Example:
int x = 34;
int y = ++x; // y is 35
The value of x is first incremented to 35, and is then assigned to y, so the values of both x and y are now 35.
2.Postfix(a++): The variable's value is first used in the expression and is then increased.
Example:
int x = 34;
int y = x++; // y is 34
x is first assigned to y, and is then incremented by one. Therefore, x becomes 35, while y is assigned the value of 34.
The same applies to the decrement operator.