How can I describe a function parameter?

Suppose there is a function: void stick(int a, inb &b, /* ? */ direct)

Actually, along with this direct I pass one of two parameters - right and left . And in the body of the function should be checked for the specified parameter.

  • 3
    Why not enum ? - VladD
  • @VladD issue in the form of a response, I used enum only once and for a very long time, I don’t even remember why he, now I read, this is what is needed - ParanoidPanda
  • one
    @ParanoidPanda Personally, I did not understand. What is direct? Why is the identifier of the third parameter not specified, but only the identifiers of the first two are indicated? What check on which parameter should occur? - Vlad from Moscow
  • @VladfromMoscow I just have long wanted to ask how you can describe your function not only through variables but also to make parameters. direct - direction. for example, we have the Travel (direct) function - and there is a check where to go. Actually everything. - ParanoidPanda

1 answer 1

Try this:

 enum Direction { Left, Right }; void stick(int a, inb &b, Direction d); { switch (d) { case Left: break; case Right: break; } // ... } 

Note that enum in C ++ to C ++ 11 versions gives a rather weak typing. For example, such code is compiled:

 enum Direction { Left, Right }; enum Direction2 { North = 5, South = 7 }; void f(Direction d) { switch (d) { case North: break; case South: break; } // ... } 

For the compiler, all enum 's are just numeric constants.

But starting with C ++ 11, it is better to use a strongly typed enum :

 enum class Direction { //^^^^^ Left, Right }; enum WrongDirection { Left = 1, Right = 0 }; void f(Direction d) { switch (d) { case Direction::Left: // а не WrongDirection::Left break; case Direction::Right: break; } // ... } 

Here the compiler will not let you accidentally use the wrong type.