Stuck to understand output..

iam new to C++..i was reading C primer plus..where i got stuck in one part..i dont understand how o/p came as mentioned in the book.
[code]
unsigned u = 10;
int i = -42;
std::cout << i + i << std::endl; // prints -84
std::cout << u + i << std::endl; // if 32-bit ints, prints 4294967264

how did it get -84..and 4294967264..\
Thank You
First Output: (-84)

this is simple, value of int i is -42, so -42+(-42)=84

Second Output: (4294967264)

Here u is unsigned and i is negative value, so they can't give a correct output. And addition of a unsigned and negative value leads to a garbage value. Actually it is not garbage, this is some kind of cyclic value.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    unsigned int a=4294967264;
    int i=32;
    cout<<a+i;
    return 0;
}


run this code with various values of i and look carefully, i think you will get your answer.
If I = -42
Then I + I will be [-42 + ( - 42 ) ]
Which will then be [- 42 - 42]
Answer = -82

It's just mathematics

Then u = 10 and I= -42
U + I = 10 + (-42)
Answer = 32
that is because of c++ implicit typecasting due to the adding of unsigned and signed ints

read this :
http://www.learncpp.com/cpp-tutorial/44-type-conversion-and-casting/
thank you guys...for your answers...
and hoity i wil surely look into dat...code u gave...
There is a rule if there is one unsigned and another is signed int than the result will be converted into unsigned that's why its output is a wrong value.

1
2
unsigned u = 10;
int i = -42; 


cout << i + i
i is signed, so output will be signed -84 (Of course it is a negative number so it'll be signed)

cout << u + i
i is signed but u is unsigned, so it will output unsigned (suppose to be -32) value as per rule but because an unsigned cannot carry negative number it'll be converted to its positive value.

If you change your variable 'i' value to '+42'
int i = 42;
You will find there is no problem.

Run the below programs and see there results and you will understand
FIRST
1
2
3
4
5
6
7
8
#include<iostream>
using namespace std;
int main()
	{
	unsigned u = 20;
	int i = -32;
	cout << u+i;
 	}

Output in my PC: 4294967284

Second
1
2
3
4
5
6
7
#include<iostream>
using namespace std;
int main()
	{
	unsigned u = -12;
	cout << u;
 	}

Output in my PC: 4294967284

As you see both of output are same as excepted
Last edited on
Topic archived. No new replies allowed.