Ask Your Question
0

Need help with example using enum in C++ programming

asked 2016-03-28 22:31:43 -0500

Thang Nguyen gravatar image

I found this link http://wiki.ros.org/CppStyleGuide#Enu... talk about using enum. But I haven't been able to use it correctly. Could you please show me an example how to use it? Thank you very much.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2016-03-29 02:29:05 -0500

ahendrix gravatar image

updated 2016-03-29 14:51:11 -0500

Does this help?

namespace Choices
{
  enum Choice
  {
     Choice1,
     Choice2,
     Choice3
  };
}
typedef Choices::Choice Choice;

int foo() {
    Choice c = Choices::Choice1;

    switch(c) {
        case Choices::Choice1:
            // TODO: something
            break;
        case Choices::Choice2:
            // TODO: something
            break;
        case Choices::Choice3:
            // TODO: something
            break;
        default:
            // TODO: something
            break;
    }
}

(tested and compiles with gcc 4.8.4)

edit flag offensive delete link more

Comments

Yes, it helps a lot. Thanks ahendrix.

But the correct should be Choices::Choice c = Choices::Choice1;

Thang Nguyen gravatar image Thang Nguyen  ( 2016-03-29 06:13:02 -0500 )edit

No; the typedef Choices::Choice Choice means that you should be able to use Choice as a type without requiring the Choices:: namespace.

ahendrix gravatar image ahendrix  ( 2016-03-29 14:49:17 -0500 )edit

I am sorry, you are correct. I define the typedef wrong so in declaring the variable I got an error which it didn't happen when I have the namespace. This makes me confused. Thank you very much :D

Thang Nguyen gravatar image Thang Nguyen  ( 2016-03-29 18:18:50 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-03-28 22:31:43 -0500

Seen: 453 times

Last updated: Mar 29 '16