Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't declare "div" in enum

I want to declare an enum with the basic math operations as the following:

enum Operations 
{
    div,
    mul,
    add,
    sub
};

but the compiler complains about this declaration as div is a reserved keyword in C++. How can I override it? or is there any solution?

Here is the error message:

error: ‘div’ redeclared as different kind of symbol /usr/include/stdlib.h:158: error: previous declaration of ‘div_t div(int, int)’

like image 501
user2362874 Avatar asked Jun 14 '14 14:06

user2362874


3 Answers

div is not a keyword, but rather a standard library function, declared in stdlib.h and possibly in cstdlib.

The simplest solution is to use different identifiers. Otherwise, you may use a scoped enumeration:

enum class Operations 
{
    div,
    mul,
    add,
    sub
};

This will put the enum's values in the Operations scope (Operations::div, Operations::mul etc.)

like image 184
juanchopanza Avatar answered Nov 10 '22 03:11

juanchopanza


Because div is a function declared in cstdlib, and the name of an unscoped enumeration may be omitted to global. This means you cannot use div as an enumeration.

in C++11, scoped enumeration is introduced for this situation

enum class Operations 
{
    div,
    mul,
    add,
    sub
};

and you can then use Operations::div

like image 28
Leo Zhuang Avatar answered Nov 10 '22 03:11

Leo Zhuang


You can create a new namespace:

#include <stdlib.h>

namespace a
{
    enum Operations
    {
        div,
        mul,
        add,
        sub
    };
}

int main()
{
    a::div;
    return 0;
}
like image 34
volperossa Avatar answered Nov 10 '22 03:11

volperossa