Reputation: 971
I am trying to figure out what is happening this code
int i = 10, j = 7, l;
unsigned int k;
double q = 3.56;
char c;
c = q * i * j;
l = c;
std::cout << l << "\n"; // result is -7
std::cout << c << "\n"; // result is ?
I couldn't understand why l result is '7', and for the c whatever i change the value i, j the result for c is always '?'. Could anyone point me a reason about that ? Thanks
Upvotes: 1
Views: 79
Reputation: 838376
The result of 3.56 * 10 * 7
is 249.2.
If the type char
on your system is a signed 8 bit value with a range from -128 to 127 then attempting to assign 249.2 will cause an overflow. If you assign to an int
instead of a char
it will be stored as 249.
The question mark is because -7 is not a printable character.
Upvotes: 6
Reputation: 516
3.56*7*10 is 249.200.....2. It becomes -7 when it is put into a char because a char is an 8 bit signed value. -7 comes from 249 (truncated) - 256.
Upvotes: 0
Reputation: 2591
You're writing the value 249.2 into a signed char which is out of the range, so it's converted to the ? character.
Upvotes: 0
Reputation: 12544
The default display method for a char is its ascii/unicode value. For values it cannot display, a ? is shown.
For others the equivalent character would be shown. For example, a char value of 65 would show A
Upvotes: 1