Consider the following code:
template<bool> class StaticAssert;
template<> class StaticAssert<true> {};
StaticAssert< (-1 < sizeof(int)) > xyz1; // Compile error
StaticAssert< (-1 > sizeof(int)) > xyz2; // OK
Why is -1 > sizeof(int)
true?
-1
is promoted to unsigned(-1)
and then unsigned(-1) > sizeof(int)
.-1 > sizeof(int)
is equivalent to -1 > size_t(4)
if sizeof(int) is 4. If this is so why -1 > size_t(4)
is false?Is this C++ standard comformant?
sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.
be the same coincidentally, as in your example). sizeof(* int) returns the size of the address value, that is, a byte. address that points to a byte position in memory that stores an int. value. The address values are typically 4 byte integers themselves on a.
sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int ).
The sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result which is size of that data type in bytes. If it is an array it will return the number of elements present in it.
The following is how standard (ISO 14882) explains abort -1 > sizeof(int)
Relational operator `>' is defined in 5.9 (expr.rel/2)
The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. ...
The usual arithmetic conversions is defined in 5 (expr/9)
... The pattern is called the usual arithmetic conversions, which are defined as following:
The integral promotions is defined in 4.5 (conv.prom/1)
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.
The result of sizeof is defined in 5.3.3 (expr.sizeof/6)
The result is a constant of type size_t
size_t is defined in C standard (ISO 9899), which is unsigned integer type.
So for -1 > sizeof(int)
, the > triggers usual arithmetic conversions. The usual arithmetic conversion converts -1 to unsigned int because int cannot represent all the value of size_t
. -1
becomes a very large number depend on platform. So -1 > sizeof(int)
is true
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With