Same code, different output in C # and C ++

FROM#:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int a = 11; int b = 2; a -= b -= a -= b += b -= a; System.Console.WriteLine(a); } } } 

Output: 27

C ++:

 #include "stdafx.h" #include<iostream> int _tmain(int argc, _TCHAR* argv[]) { int a = 11; int b = 2; a -= b -= a -= b += b -= a; std::cout<<a<<std::endl; return 0; } 

Output: 76

The same code has excellent output, can anyone tell me why this is so? Help rate!

+4
source share
1 answer

In C #, your code is well defined and equivalent to the following:

 a = a - (b = b - (a = a - (b = b + (b = b - a)))); 

The most internal assignments are not relevant here, because the assigned value is never used until the variable is reassigned. This code has the same effect:

 a = a - (b = b - (a - (b + (b - a)))); 

This is about the same as:

 a = a - (b = (b * 3) - (a * 2)); 

Or even simpler:

 b = (b * 3) - (a * 2); a -= b; 

However, in C ++, your code gives undefined behavior. There is no guarantee what she will do.

+14
source

Source: https://habr.com/ru/post/1416295/


All Articles