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

Can I check built-in type at runtime?

例如,

如果我写:

char c = CHAR_MAX;
c++;

我能知道 'c++' 是否会导致 intchar 以便我确定它是否溢出吗?

我不知道你所说的 "check at runtime" 是什么意思,但我可以肯定地告诉你 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. in comment, you should check if c == CHAR_MAX prior to incrementing. For more about checking for signed overflow, see Detecting signed overflow in C/C++所述。

Can I know if 'c++' results in int or char

根据 中的标准引用,您可以知道它会导致 char

so I know for sure if its not an overflow?

你可以确定是溢出了。在 char 是有符号类型的系统上,据我所知程序的行为将是未定义的。

Can I check built-in type at runtime?

您无法在 运行时 检查 built-in 类型,但您可以在 编译时 检查它们。例如:

static_assert(std::is_same_v<decltype(c++), char>);

when I say: signed char c = CHAR_MAX + 1 then CHAR_MAX + 1 becomes int result and then in is assigned to c which is implementation-defined.

确实如此。除了在 sizeof(signed char) == sizeof(int) 的奇异系统上,在这种情况下没有提升,并且算术导致溢出,这是未定义的行为。

并且仅在 C++20 之前。自 C++20 起,具有不可表示值的签名初始化由标准定义。

Can I ever make signed char overflow?

是的。使用增量运算符。据我所知,该标准并未提及增量运算符内的提升。但是,这可能有待解释。