0

I'd like to know how this cast works :

int value = 100;
auto f = [&value] (int x, int y) -> char { return x + y + value; };
printf("%d\n", f(10, 20));
value = 200;
printf("%d\n", f(10, 20));
return 0;

It prints -126 and -30 but i don't understand how is it possible to print a negative integer.

1 Answers1

0

The numerical range for char is -128..127. 10 + 20 + 100 is 130 and outside of that range, so it wraps around when expressed as char.

To fix you need to use a data type that can contain values large enough:

auto f = [&value] (int x, int y) -> int { return x + y + value; };

Or use values < 127.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • it's an example from my OOP course, not some code written by me. Can you please explain the calculation such that the example lead to -126 and -30? I didn't really understand how it "wraps" around –  Jun 19 '19 at 20:06
  • 1
    Signed integer numbers in modern machines are stored in [Two's Complement](https://en.wikipedia.org/wiki/Two's_complement). An 8-bit value (`char`) can either be unsigned (`0`..`255`) or signed with Two's Complement (`-128`..`127`). No other values can be represented. In the case of signed, `char x = 127 + 1` assigns `-128` to `x`. In your case, 130 is precisely 3 over the limit, so it's the same as `127 + 3` where that's `-126` wrapped around. – tadman Jun 19 '19 at 20:13