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)’
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.)
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
You can create a new namespace:
#include <stdlib.h>
namespace a
{
enum Operations
{
div,
mul,
add,
sub
};
}
int main()
{
a::div;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With