c# und c++ rechnen anders?

hallo leute,

habe mich gerade hier angemeldet weil mich ein problem ziemlich fuchst bzw. ich nun auch beim kontrollieren zwei ergebnisse bekomme. da ich normal nur still mitlese, bin ich mir sicher das ihr mir das locker erklären könnt.

folgende aufgabe:

int i = 1;

i += i++ + ++1;

--
ich arbeite mit c# und für mich war, als ich mir das kurz im kopf überschlagen habe, die einzige lösung: 5;
wir wissen alle - kontrolle ist besser:
int i = 1;
i += i++ + ++i;
Console.WriteLine("I : " + i);
Console.ReadLine();

.... Ergebnis: 5;

nun aber das für mich (kenne mich mit c++ nicht gut aus) komische.
wenn ich das ganze in c++ ausführe, erhalte ich 7.

int i = 1;
i += i++ + ++i;
cout << i << "\n";
system("pause");
return EXIT_SUCCESS;

macht wenn man mit dem i++ anfängt auch sinn... aber wie kann es sein, dass hier zwei verschiedene ergebnisse ausgegeben werden? ich dachte immer, c# baut teilweise auf c++ auf... bzw. warum wird hier anders gerechnet? wäre schön wenn mich jemand erleuchtet...ich schlag sonst noch den kopf aufn tisch!

wären die zwei sprachen von unterschiedlichen firmen entwickelt worden, könnt ich mir das ja noch erklären, aber so? X(
 
Die Antwort ist ganz einfach - es ist undefiniert (DAS, und nicht etwa die arachaisch anmutende manuelle Speicherverwaltung, ist einer der Gründe für die "Missgunst" der Sprache bei so einigen Leuten ;) )
Stroustrup: C++ Style and Technique FAQ
Stroustrup: C++ Style and Technique FAQ
Code:
		int j = [COLOR=black]++i +[/COLOR] i++;	// value of j unspecified
		f(out1(),out2());	// prints 12 or 21
	}
The value of j is unspecified to allow compilers to produce optimal code. It is claimed that the difference between what can be produced giving the compiler this freedom and requiring "ordinary left-to-right evaluation" can be significant. I'm unconvinced, but with innumerable compilers "out there" taking advantage of the freedom and some people passionately defending that freedom, a change would be difficult and could take decades to penetrate to the distant corners of the C and C++ worlds. I am disappointed that not all compilers warn against code such as ++i+i++. Similarly, the order of evaluation of arguments is unspecified. IMO far too many "things" are left undefined, unspecified, implementation-defined, etc. However, that's easy to say and even to give examples of, but hard to fix. It should also be noted that it is not all that difficult to avoid most of the problems and produce portable code.
 
Zurück
Oben