+ 2
Enum declaration
enum Abc { i = 0, j = 1 }; enum {idd= 100 }; I am aware about first syntax of enum declaration. What is use of second declaration? I mean what is name of enum in it and why it is allowed in c++?
5 ответов
+ 5
Personally, I've never used enum without a name, but I found some posts about this:
cppreference( https://en.cppreference.com/w/cpp/language/enum ): The name of an unscoped enumeration (enum without class or struct) may be omitted: such declaration only introduces the enumerators into the enclosing scope:
enum { a, b, c = 0, d = a + 2 }; // defines a = 0, b = 1, c = 0, d = 2
A Stack Overflow post about 'Anonymous enum' can be found here: https://stackoverflow.com/questions/7147008/the-usage-of-anonymous-enums/7147049
+ 2
CarrieForle so, technically, what's the difference between using:
#define y 100
and:
enum {y=100};
?
+ 1
The elements of enum are of compile-time constant. This applies to both unscoped and scoped.
In the following example:
#include <iostream>
using namespace std;
enum A {a, b=100};
enum {x, y=100};
enum class C {apple};
int main() {
cout << &(A::a);
cout << &x;
cout << &(C::apple);
return 0;
}
3 Errors occurred from 3 cout statements are all that the address operator requires lvalue operand. This means the elements don't have addresses, which apply to the compile-time constant behavior. They don't consume any memory.
+ 1
visph
One is a marco, can define anything other than a 'constant integer', and the other is a (seris of) constant values. Though if you look at the result, they appears to be the same. #define is just another way to achieve it.
But how about:
#define a 0
#define b 1
#define c 2
#define d 3
vs
enum {a, b, c, d};
Interestingly enough, there is a comparison between these 'in C' in Stack Overflow, with one more opponent 'static const'.
https://stackoverflow.com/questions/1674032/static-const-vs-define-vs-enum
0
Thanks CarrieForle ... I have also not used it but came across same in MFC examples.
Also I got point that enum value cannot be accidently changed unlike int , but don't understand how it doesnot consume memory..
Refer below code and all three enum member including unnamed enum prints size as 4 same as int
enum A{i=0};
enum {idd=12};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(i) << endl;
cout << sizeof(idd) << endl;
//gives error
//idd= 13;
return 0;
}