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

前端 未结 4 1898
既然无缘
既然无缘 2021-02-19 15:04

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:23

    Is this well defined behaviour or is it undefined

    This is well defined behaviour.

    In your code

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

    foo is unambiguous. The local or inner foo "shadows" (or hides) the outer foo. So, it is essentially

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

    To quote C11, chapter §6.2.1, "Scopes of identifiers", (emphasis mine)

    If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

    Now, to answer the second part,

    If it is well defined, is there a way I could obtain the size of the datatype foo without declaring a variable of that type to only use sizeof on it?

    Well, a scope of the inner foo identifier starts after it's definition (as a char type variable). So, if you use foo (the typedefed type) before the definition of variable foo, you'll be actually seeing the global definition, as till that point , variable foo is not present to "shadow out" the global identifier foo.

    As mentioned in the other answer by Mr. Purag, you can surely do something like

    #include 
    
    typedef int foo;
    
    int main(void)
    {
        printf ("%zu\n", sizeof foo); /* will cosider the global */
        char foo = 0;                 /* Global definition gets shadowed here*/
        printf ("%zu\n", sizeof foo); /* The local definition of 'foo' is only visible*/ 
                                      /* till the end of the block (function)*/
    
        return 0;
    }
    

    That said, as a note, the type of the result of sizeof operator is size_t. You should be using %zu format specifier to print the result.

提交回复
热议问题