2

This question is similar to, but more specific than, this other question:

using struct keyword in variable declaration in C++.

Consider the following program:

#include <stdio.h>

struct Foo {
    int x;
    int y;
};

Foo getFoo() {
    Foo foo;
    return foo;
}

int main(){
    getFoo();
}

The above program compiles with g++ but not gcc.

We can modify the program as follows to make it compile with both gcc and g++:

#include <stdio.h>

struct Foo {
    int x;
    int y;
};

struct Foo getFoo() {
    struct Foo foo;
    return foo;
}

int main(){
    getFoo();
}

Is this use of the struct keyword guaranteed by the standard to be well-defined in C++?

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
merlin2011
  • 67,488
  • 40
  • 178
  • 299
  • Another way to write code that compiles in both compilers is to start with code similar to the first example and just add a `typedef` for the struct type: `typedef struct Foo Foo;` then you don't have to use `struct Foo` everywhere. – Remy Lebeau Aug 10 '18 at 03:36
  • @RemyLebeau, Is the statement `typedef struct Foo Foo;` also well-defined in C++ for the same reason as the given answer? – merlin2011 Aug 10 '18 at 07:36
  • I don't know. But typedefing a struct type is common practice in C. And you can wrap the typedef inside of `#ifndef __cplusplus` to skip it in C++, if you want` – Remy Lebeau Aug 10 '18 at 16:12

1 Answers1

4

Yes. That's known as an elaborated-type-specifier.

T.C.
  • 129,563
  • 16
  • 274
  • 404