Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between these two declarations? [duplicate]

Tags:

c++

I am only asking in context of C++.

struct x1 { ... };
typedef struct { ... } x2;
int main()
{
    x1 a;
    x2 b;
}
like image 346
user3865070 Avatar asked Jan 31 '16 13:01

user3865070


1 Answers

The first defines a class with the name x1.

The second defines an unnamed class and also defines a type alias, by the name x2 to it.

The difference is very subtle in C++. You can observe the difference by trying to declare a function by the same name:

void x1(); // OK
void x2(); // not OK, redefined as a different type of symbol

In practice, you should avoid defining a function by the same name as a class within the same namespace, so this difference hardly ever comes up. The first one is typically preferred because it's simpler.

In C, the difference affects the use of the identifier a bit more.

like image 92
eerorika Avatar answered Sep 30 '22 20:09

eerorika