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
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>
usingnamespace std;
int main()
{
unsignedint 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.
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>
usingnamespace 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>
usingnamespace std;
int main()
{
unsigned u = -12;
cout << u;
}