-
output : 2 4 8 16 32 but when i run the same code in C/C++ i get this,
Output: 3 7 15 31 63 It looks like C# is ignoring to do X++ at the end where c++ does the post increment. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
In CSharp we evaluate always from left to right - first So x is first 1. The right hand side of In C++ a compiler can evaluate from left to right or from right to left - there we have no strict eval order. This is why your code is UB (undefined behaviour) in C++. See: https://godbolt.org/z/YjTx9E1nE When we evaluate from right to left we start with To get the intended result you can write: int x = 1;
for (int i = 0; i < 5; i++)
{
x = x++ + x;
Console.WriteLine(x);
} or using System;
int x = 1;
for (int i = 0; i < 5; i++)
{
x = x+ ++x;
Console.WriteLine(x);
} or using System;
int x = 1;
for (int i = 0; i < 5; i++)
{
x = x+ x +1;
Console.WriteLine(x);
} or using System;
int x = 1;
for (int i = 0; i < 5; i++)
{
x = (x <<1) +1;
Console.WriteLine(x);
} |
Beta Was this translation helpful? Give feedback.
x += x++;
is the same asx = x + x++
;In CSharp we evaluate always from left to right - first
x
, thanx++
;So x is first 1.
x++ is evaluated to 1, too (it is the post increment operator).
After the evaluation x is incremented by one and assigned to
x
.The right hand side of
x = x + x++
is evaluated to1 +1
which is 2.After the evaluation of the right hand side - the result is assigned to x....
The side effect of evaluating
x++
is lost.In C++ a compiler can evaluate from left to right or from right to left - there we have no strict eval order. This is why your code is UB (undefined behaviour) in C++.
See: https://godbolt.org/z/YjTx9E1nE
When we evaluate from right to left we start with
x++