In C++11, I know I can use fpclassify() to check for invalid floats, but checking for invalid integers doesn't seem to have a corresponding function available. I have tried:
> All combinations of bits in an integer variable are valid integer values
Only for narrow character types (char, signed char, unsigned char):
For narrow character types, all bits of the object representation participate in the value representation. For unsigned narrow character types, each possible bit pattern of the value representation represents a distinct number. These requirements do not hold for other types - IS
To eschew undefined behaviour with integer types, all we need to do is:
a. initialise an object before its value is used.
b. for signed integer types, avoid arithmetic overflow.
c. ensure that the second operand of / and % is not zero.
Integer types do not have categories: there is no special representations for some ranges (like sub-normal for floating point), they can't represent infinity, and and there is no concept of 'not a number' for integer types. There is no classification of integer types.
technically, there are architectures with NaTs (not-a-thing, the integer equivalent of the floating-point NaNs). C++ spec calls them "trap representations", but this program doesn't generate any.
@mdavidjohnson
you forgot to enable diagnostics g++ -Wall -pedantic-errors gives me
1 2 3 4 5
main.cpp:13:7: error: integer constant is too large for its type
i = 987654321987654321987654321987654321;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp: In function 'int main()':
main.cpp:13:7: warning: overflow in implicit constant conversion [-Woverflow]
and clang++, similarly
1 2 3 4 5 6 7
main.cpp:13:7: error: integer literal is too large to be represented in any integer type
i = 987654321987654321987654321987654321;
^
main.cpp:13:7: warning: implicit conversion from 'unsigned long long' to 'int' changes value from 5235031781615866545 to 1125651121 [-Wconstant-conversion]
i = 987654321987654321987654321987654321;
~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.
Also, nothing in your try block can throw exceptions.
can a valid C++ program (one without undefined behaviour) generate a trap representation for an integer?
I don't think so; any path that leads to a trap is supposed to be specified as undefined behavior (for ia64 NaTs those could be reading an uninitialized local or mismatching a callback function signature)