gpt4 book ai didi

c++ - 我可以在运行时检查内置类型吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:34 26 4
gpt4 key购买 nike

例如,

如果我写:

char c = CHAR_MAX;
c++;

我能否知道“c++”的结果是 int 还是 char,以便我确定它是否不是溢出?

最佳答案

我不知道你所说的“运行时检查”是什么意思,但我可以肯定地告诉你,c++ 会产生 char 类型的纯右值,并且c 始终是 charc 永远不会转换为 int

根据 [expr.post.incr]/1 :

The value of a postfix ++ expression is the value of its operand. [ Note: The value obtained is a copy of the original value — end note ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a complete object type. The value of the operand object is modified by adding 1 to it. The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. — end note ] The result is a prvalue. The type of the result is the cv-unqualified version of the type of the operand. If the operand is a bit-field that cannot represent the incremented value, the resulting value of the bit-field is implementation-defined. See also [expr.add] and [expr.ass].

Nikos C. 所述在评论中,您应该在递增之前检查是否 c == CHAR_MAX。有关检查签名溢出的更多信息,请参阅 Detecting signed overflow in C/C++ .

关于c++ - 我可以在运行时检查内置类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com