[英]Difference in type conversion between C and C++?
The last example in this tutorial regarding Implicit type conversion states that std::cout << 5u - 10;
本教程中关于隐式类型转换的最后一个示例指出std::cout << 5u - 10;
will produce 4294967291
rather than -5
due to type conversion.由于类型转换,将产生4294967291
而不是-5
。 I tried this in both C and C++.我在 C 和 C++ 中都试过这个。 The result in C++ was as promised, however when using C ( printf("%d\\n", 5u - 10);
) the result was -5
. C++ 中的结果与承诺的一样,但是当使用 C ( printf("%d\\n", 5u - 10);
) 时,结果是-5
。 What happened?发生了什么?
In the C example there is no type conversion whatsoever.在 C 示例中,没有任何类型转换。 C just evaluates the expression 5u - 10
and pushes the result onto the stack. C 只是计算表达式5u - 10
并将结果压入堆栈。 Then printf sees a type character and interprets the value on the stack as such when printing it.然后 printf 看到一个类型字符并在打印它时解释堆栈上的值。 The type character is d
( %d
) meaning "decimal integer" and hence the position on the stack is retrieved as an int and is printed as (signed) decimal.类型字符是d
( %d
) 表示“十进制整数”,因此堆栈上的位置作为 int 检索并打印为(有符号)十进制。
Would the type character be for example ld
( %ld
), the position on the stack would be retrieved as a long, even if only an int was pushed, and that would be printed as a (signed) decimal number.例如,如果类型字符是ld
( %ld
),则堆栈上的位置将作为 long 检索,即使只推送了一个 int,也将打印为(有符号的)十进制数。 Again, there is no type conversion whatsoever (there will just be a nonsense number printed).同样,没有任何类型转换(只会打印一个无意义的数字)。
A little more thought brought upon the realization that the problem was with the printf
rather than the conversion itself.多一点思考后意识到问题出在printf
而不是转换本身。 Notice that what was written was printf("%d")
.请注意,写入的是printf("%d")
。 This performed yet another conversion back to signed int
, which is why I saw the result of -5
.这执行了又一次转换回有signed int
,这就是为什么我看到-5
的结果。
When testing with printf("%u")
, the promised result ( 4294967291
) was shown.使用printf("%u")
进行测试时,显示了承诺的结果( 4294967291
)。
To cap it off, printf("%X")
resulted in FFFFFFFB
which means both those values, depending on a signed or unsigned interpretation.为了结束它, printf("%X")
导致FFFFFFFB
这意味着这两个值,取决于有符号或无符号解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.