简体   繁体   English

从int转换为char

[英]Cast from int to char

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. 它打印-126和-30但我不明白如何打印负整数。

The numerical range for char is -128 .. 127 . char的数值范围是-128 .. 127 10 + 20 + 100 is 130 and outside of that range, so it wraps around when expressed as char . 10 + 20 + 100130并且在该范围之外,因此当表示为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. 或使用值<127。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM