0

I have a requirement to add some extra data into an existing enumeration code based on a scenario. As a sample I have the below code:

#include <iostream>

enum Permissions {Readable = 0x4, Writable = 0x2, Executable = 0x1};

int main()
{
Permissions perms = static_cast<Permissions>(Executable | static_cast<Permissions>(29));
std::cout << perms  <<  std::endl;
perms &= ~Permissions::Executable;
std::cout << perms  <<  std::endl;
}

At first I am trying to add the data and later extract the same - but I get compilation error:

$ c++ -std=c++11 try67.cpp
try67.cpp: In function 'int main()':
try67.cpp:9:7: error: invalid conversion from 'int' to 'Permissions' [-fpermissive]
 perms &= ~Permissions::Executable;

Is the approach correct and how can we remove the compilation error?

Programmer
  • 8,303
  • 23
  • 78
  • 162

1 Answers1

3

Is the approach correct and how can we remove the compilation error?

The approach is subject to problems. If you work with your variables carefully, you can get by with using the enum.

The line

perms &= ~Permissions::Executable;

is equivalent to

perms = perms & ~Permissions::Executable;

The cause of the compiler error is that the bitwise operators result in an int and you are trying to assign an int to an enum without a cast.

You'll have to use a cast just like you did with the first operation to get rid of the compiler error.

perms = static_cast<Permissions>(perms & ~Permissions::Executable);

Update, in response to OP's comment

The value Readable | Writable is 0x6, which does not correspond to the value of any of the tokens in the enum. Hence, if you use:

Permissions p1 = Permissions::Readable;
Permissions p2 = Permissions::Writable;

Permissions p3 = static_cast<Permissions>(p1 | p2);

you will have a case where the value of p3 does not match any of the known tokens. If you have if/else blocks or switch statements that expect the values of all variables of type Permissions to be one of the known tokens, you will notice unexpected behavior in your code.

R Sahu
  • 204,454
  • 14
  • 159
  • 270