Wheels2050
Wheels2050

Reputation: 889

Why does the compiler not complain when the struct keyword is reused in a function, with a variable declaration?

Sorry about the vague question, I was unsure of how to be specific while being concise. I noticed the following behaviour when looking at a colleague's code, and I don't understand why the compiler (GCC 4.8.2) doesn't complain. Here is a trivial example:

#include <iostream>

using namespace std;

struct mystruct {
  int val;
};

int main()
{
  struct mystruct x; //What is the compiler doing here?

  /* Do something with x here */
  return(0);
}

How is the compiler treating the line struct mystruct x;? If it treated it as a declaration of some local struct called mystruct and initialisation of an instance called x, why am I allowed to treat x as an instance of the mystruct defined in the global scope?

My other thought was that it might be acting like a forward declaration, but I wasn't aware that one could declare an instance of a class at the same time as making a forward declaration. Is that simply what's happening here, though (and it's effectively doing nothing other than declaring the variable, since mystruct is already defined)?

Upvotes: 1

Views: 193

Answers (3)

Paul Rooney
Paul Rooney

Reputation: 21619

It's c syntax and as such valid for c++.

In c you would be required to use typedef if you wished to drop the struct keyword in the declaration.

Indeed if you declare the the typedef'd and untypedef'd name, you can initialise using either syntax.

e.g.

typedef struct mystruct {
  int val;
} mystruct;

int main()
{
  mystruct x;
  struct mystruct x2;

  /* Do something with x here */
  return(0);
}

For c++ The use of typedef in the declaration of a struct is not required and so the use of struct in the declaration of an instance is optional, supported mainly for legacy reasons.

If you find yourself working on a cross C/C++ code base it will be useful to understand how both can play together happily like this.

Upvotes: 3

Drew Dormann
Drew Dormann

Reputation: 63946

struct mystruct is synonymous with mystruct, assuming that such a struct has already been declared.

The word struct in this context is

  • Completely optional in C++
  • Potentially a readability aid, if you're prone to think that it's an enum or some other type
  • A carryover from the C language, where it would have been required, given similar code.

Upvotes: 1

b4hand
b4hand

Reputation: 9770

The compiler doesn't complain because there is nothing wrong with your code. You have done exactly what you have described. You have defined x to be a variable of type mystruct.

You may be unfamiliar with this form, but in C, it is the only way to declare variables to have a struct type. It's less common in C++ because the struct keyword was made optional in this context; however, C++ maintains compatibility with the traditional C syntax.

Upvotes: 3

Related Questions