Unexplained result.

Hey guys so i was practicing some basic c++ and i think i came across a compiler error but im not 100% sure. I typed down my code and expected a result of 2 and then 2 results of 10 but i got bizare results instead.

Heres my code:

#include <iostream>
using namespace std;

int main()
int a , b;
a = 5 - (b = 3);
cout << a << endl;

int c , d , e;
c = 10;
c = d = e;

cout << e << endl;
cout << d << endl;
return 0;

expected answer:

Actual answer from compiler:

Can someone explain to me where these crazy figures came from ??

c = d = e;

is equivalent to

d = e;
c = d;

However, e is never initialized, so all three variables now contain garbage.

Edit: if you want to "fix" your program, write this instead:

e = d = c;
Last edited on
why is this and how does it make such a weird number ?
A variable that is declared without initialization contains garbage. In other words, take

int a;
cout << a;

What do you expect this to display?
However, e is never initialized
why is this

Because you haven't initialised it anywhere.

You initialise c to 20, but you then change the value of c to the result of (d = e), which is undefined, because the value of e is undefined.

If you want e to be initialised, you have to initialise it.
Last edited on
but those wacky numbers had to come from somewhere right ?? i mean the compiler didnt just decide that -1134330576 was a nice negative number and lets use it??
Yeah, but it's undefined. There's no way of knowing why it's that number. Maybe it's left over from some previous data that was at the location that's now being used for your uninitialised variable. Maybe it's some strange number your specific compiler writes to unitialised memory.

As far as you're concerned, it might as well be random. That's what you get when you don't initialise variables - undefined behaviour.
It's nothing to do with the compiler 'deciding numbers'.

you ask the compiler for an int called i for example and it'll give you a bit of space for it in memory. it is YOUR responsibility to give it an initial value. if you dont it'll use the value that's already at that memory location.
Last edited on
okay i seee thanks guys :) that helped me understand it a bit better. so if i want to give c,d and e the same value will c=d=e=5; work or what should i use ??
Yes, that will work.

It will first evaluate:

e = 5


d = (e = 5)


c = (d = (e = 5))

The result of evaluating each expression is 5.
okay thanks mikey and the rest of you. great help thanks guys. im only new and decided to learn c++ to start making games. i know that im a long way of but i think its a cool idea to understand a coding language to some extent . :)
Topic archived. No new replies allowed.