Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ warning when using optional 'struct' keyword

If I write this program:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}

and compile it with:

g++ main.cxx -Wall -Wextra

It gives me this warning:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

However, if I take out the struct keyword after the new keyword:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}

and compile it the same way, g++ outputs no warnings. Why does g++ output that warning if I use the struct keyword?

like image 550
Adetque Avatar asked Jun 01 '11 20:06

Adetque


2 Answers

In C++, the struct keyword defines a type, and the new type no longer needs the struct keyword. This is one of the many differences between C and C++.

like image 165
Thomas Matthews Avatar answered Oct 24 '22 19:10

Thomas Matthews


Examining the error:

main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

g++ thinks you're declaring a new struct with the name foo::bar instead of allocating memory of type struct foo::bar. My guess would be because g++ assumes any usage of struct that doesn't declare an lvalue is for the purpose of declaring a type.

like image 27
tyree731 Avatar answered Oct 24 '22 20:10

tyree731