6

Say I have

struct mystruct
{
};

Is there a difference between:

void foo(struct mystruct x){}

and

void foo(mystruct x){}

?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625

3 Answers3

11

In C the latter isn't valid.

However in C++ they're almost the same: The first one would be valid if you haven't yet declared your struct at all, it would treat it as a forward declaration of the parameter all in one.

Mark B
  • 95,107
  • 10
  • 109
  • 188
7

Not in the code you've written. The only difference I know of between using a defined class name with and without struct is the following:

struct mystruct
{
};

void mystruct() {}

void foo(struct mystruct x){} // compiles
void foo(mystruct x){} // doesn't - for compatibility with C "mystruct" means the function

So, don't define a function with the same name as a class.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • Insidious - since when are you allowed to have a function of the same name as a type? – Kerrek SB Sep 08 '11 at 13:43
  • @Kerrek: same name as a struct, since K&R C. structs occupy a different namespace from typedefs and functions. IIRC the way C++ introduces `mystruct` for use without the `struct` prefix isn't actually by typedefing it, there's just a name resolution rule somewhere that says if you can't find a name in scope, check for a struct in that scope before moving on to the next scope. – Steve Jessop Sep 08 '11 at 13:43
  • Nice, didn't know you could do that. Thanks! – Luchian Grigore Sep 08 '11 at 13:45
3

No difference. The latter is the correct C++ syntax; the former is permissible as a legacy variant for recovering C programmers.

Note that struct and class are essentially the same and both define a class, so there's no special treatment for C-style POD structs in C++.

[Edit: Apparently there is a small difference, see Mark B's excellent answer.]

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084