2

I have 2 enums.

typedef enum {
 BLUE = 1,
 RED = 2
} FavoriteColor;

typedef enum {
 ORANGE = 1,
 YELLOW = 2,
 RED = 3
} Color;

In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?

user2864740
  • 60,010
  • 15
  • 145
  • 220
neo
  • 1,952
  • 2
  • 19
  • 39
  • 2
    Notice all of the enums in the iOS or Mac APIs. All of the enum values have names related to the enum. So you want `FavoriteRed` and `ColorRed`, for example. – rmaddy Feb 19 '14 at 21:16
  • I prefer using instances of `NSString` instead of `int` objects. `@"com.mycompany.myapp.FavoriteColor.RED"`, … Okay, you lose switch(). Is this a disadvantage? ;-) – Amin Negm-Awad Feb 19 '14 at 21:23

3 Answers3

5

You can't. And the compiler should warn you about that.

enum constants live in the global namespace. The second definition is a redefinition that should produce an error.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
1

It is not possible to have scoped enumerations. The general way around this is to use prefixes which appear in most libraries like UIKit. You should define your enumerations like this:

typedef enum {
 FavoriteColorBlue = 1,
 FavoriteColorRed= 2
} FavoriteColor;

typedef enum {
 ColorOrange = 1,
 ColorYellow = 2,
 ColorRed= 3
} Color;

The only other way would be to use a class with static access to constants as described here.

Community
  • 1
  • 1
Dan Watkins
  • 918
  • 9
  • 25
0

use enum class instead just enum. Then you can use the same names for different enums;

    // ConsoleApplication3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

enum class window {large,small};
enum class box {large,small};




int main()
{
    window mywindow;
    box mybox;
    mywindow = window::small;
    mybox = box::small;
    if (mywindow == window::small)
        cout << "mywindow is small" << endl;
    if (mybox == box::small)
        cout << "mybox is small" << endl;
    mybox = box::large;
    if (mybox != box::small)
        cout << "mybox is not small" << endl;
    cout << endl;

}
rauprog
  • 243
  • 3
  • 9