Search code examples
c++syntaxcastingsizeof

What does sizeof(int(123)) mean?


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?


Solution

  • 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.