Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof on a typedef instead of a local variable

Like in this example (in C):

typedef int type;

int main()
{
    char type;
    printf("sizeof(type) == %zu\n", sizeof(type)); // Outputs 1
}

The output is always the size of the local variable type.

When C++ removed the need to write struct before each use of a structure it still preserved the struct {type} syntax and introduced an alias (class {type}) to explicitly refer to a structure or class.

Example (in C++):

struct type {
    int m;
};

int main()
{
    char type;
    printf("sizeof(type) == %u\n", sizeof(type)); // Outputs 1
    printf("sizeof(struct type) == %u\n", sizeof(struct type)); // Outputs 4
    printf("sizeof(class type) == %u\n", sizeof(class type)); // Outputs 4
}

My question is if there is a way to explicitly refer to a typedef in C or C++. Something like sizeof(typedef type) perhaps (but that does not work).

I know that it is common practice to use different naming conventions for variables and types to avoid these kinds of situations but I would still like to know if there is a way within the langauge to do this or if there is not. :)

like image 306
wefwefa3 Avatar asked Nov 26 '14 15:11

wefwefa3


1 Answers

There is no way to resolve this one but if your structure is defined globally you can use this,

Scope resolution operator ::.

printf("sizeof(type) == %zu\n", sizeof(::type));
like image 159
Venkatesh Avatar answered Oct 05 '22 16:10

Venkatesh