Search code examples
c++c++17typechecking

Can I check built-in type at runtime?


For example,

If I write:

char c = CHAR_MAX;
c++;

Can I know if 'c++' results in int or char so I know for sure if its not an overflow?


Solution

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

    As per standard quote in L.F.'s answer, you can know that it results in char.

    so I know for sure if its not an overflow?

    You can know for sure that it is an overflow. On systems where char is a signed type, the behaviour of the program will be undefined as far as I can tell.

    Can I check built-in type at runtime?

    You cannot check built-in types at runtime, but you can check them already at compiletime. For example:

    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.

    Indeed. Except on exotic systems where sizeof(signed char) == sizeof(int) in which case there is no promotion, and the arithmetic causes overflow which is undefined behaviour.

    And only until C++20. Since C++20, signed initialisation with unrepresentable value is defined by the standard.

    Can I ever make signed char overflow?

    Yes. Using the increment operator. As far as I can tell, the standard says nothing about promotion within the increment operator. However, this may be open to interpretation.