Is using sizeof on a variable where a type of the same name exists well defined?

前端 未结 4 1415
忘掉有多难
忘掉有多难 2021-02-19 14:56

Is this well defined behaviour or is it undefined / somehow else defined which foo (data type or identifier) sizeof will be operating on ?



        
4条回答
  •  礼貌的吻别
    2021-02-19 15:25

    First of all according to the C Standard (6.5.3.4 The sizeof and alignof operators)

    2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

    Thus it is the type of the operand of the sizeof operator that determinates the size of the operand. So you may use interchangeably either an expression or some type definition.

    Take into account that an expression used in the sizeof operator is not evaluated.

    For example you can write

    int x = 10;
    printf( "%zu\n", sizeof( ++x ) );
    

    and after the printf x will have the same value 10 as before the printf.

    As for your code snippet it seems that you made a mistake. I think you mean the following

    typedef int foo;
    
    int main(int argc, char *argv[])
    {
        foo exp;
        printf ("%zu\r\n", sizeof( exp ));
        return 0;
    }
    

    Of course there is no need to create an object of type foo. You could write simply

        printf ("%zu\r\n", sizeof( foo ));
    

    As for your original code

    typedef int foo;
    
    int main(int argc, char *argv[])
    {
        char foo;
        printf ("%u\r\n", sizeof(foo));
        return 0;
    }
    

    then identifier name foo in the block scope of function main hides the type definition foo in the global scope and statement

        printf ("%u\r\n", sizeof(foo));
    

    is equivalent to

        printf ("%u\r\n", sizeof( char ));
    

    In C you can't refer to the global definition of foo in this case.

提交回复
热议问题