I'm surprised why the following code would compile:
#include <stdio.h>
int main(){
printf("%lu",sizeof(int(123)));
return 0;
}
the output is 4, what is the meaning of (123) here?
And I found this line of code can compile with g++, but not gcc, what is the reason?
This is C++, the int(123) is a function-style cast to int. It's of course pointless, since 123 is an int-typed literal anyway.
Function-style casts are not part of C, which is why it won't build with a C compiler.
To answer more of the question, what happens is that the operator sizeof is compile-time evaluated to the size (in chars) of its argument. The argument is of type int, so you output the size of int on your platform which is 4.
You could also have used just a plain sizeof 123, which would build in C, or sizeof (int) to be explicit about the type instead of deriving it from a value. Note that the parentheses are part of the argument (the type name is written as a C-style cast), sizeof is not a function.
int(123) is an expression with using explicit type conversion.
From the C++ Standard (5.2.3 Explicit type conversion (functional notation))
1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4)...
As for the sizeof operator then (C++ STandard, 5.3.3 Sizeof)
1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id...
Thus in this expression
sizeof(int(123))
there is used explicit conversion of an integer literal of type int to the type int (that does not make great sense) and the sizeof operator is applied to the expression that yields the result of the type size_t.
In fact this expression is equivalent to
sizeof(int)
or in this particular case to
sizeof(123)
because the integer literal 123 has the type int.
The form of the explicit conversion of the functional notation is valid only in C++. In C such a notation of conversion is absent.
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