1

What is the point of using the enum keyword in the function parameter? It seems to do the same thing without it.

enum myEnum{
  A, B, C
};

void x(myEnum e){}

void y(enum myEnum e){}

Is there a difference between the two?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
TigerFace
  • 13
  • 3
  • 1
    Probably C compatibility. C has different rules about when identifiers are treated as types and tends to require you be more explicit about using the `enum` and `struct` keywords. So for example in C [x doesn't compile](https://godbolt.org/z/8jMz4TPjf) and you actually need to write the `y` version. It doesn't hurt anything for C++ to maintain this compatibility with C syntax. – Nathan Pierson Sep 21 '21 at 21:46

1 Answers1

1

In this function declaration

void x(myEnum e){}

the enumeration myEnum shall be already declared and not hidden.

In this function declaration

void y(enum myEnum e){}

there is used the so-called elaborated type name. If in the scope there is declared for example a variable with the name myEnum like

int myEnum;

then using this function declaration

void y(enum myEnum e){}

allows to refer to the enumeration with the name myEnum that without the keyword enum would be hidden by the declaration of the variable.

Here is a demonstrative program.

#include <iostream>

enum myEnum{
  A, B, C
};

void x(myEnum e){}

int myEnum; 

//  compiler error
//void y(myEnum e){} 

void y(enum myEnum e){}

int main() {
    // your code goes here
    return 0;
}

As it is seen the commented function declaration will not compile if to uncomment it.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Note (OT-ish): It's probably a good thing to mention C++11 enum classes. `enum class myEnum` gets its own scope and will lead to fewer surprises – Fluffy Sep 21 '21 at 21:52