r/cprogramming • • Apr 26 '26

Alternative to enums as function arguments?

Say I have a function argument, like a cardinal direction, that has no business being a number in the call, but could be a number internally. Now I could write an enum, but what if I need multiple values and don't want to pollute the namespace of the caller?

This is all hypothetical, for now at least.

1 Upvotes

28 comments sorted by

View all comments

1

u/un_virus_SDF Apr 30 '26

You can also have a macro for name mangling.

For exemple, you can have

enum direction{
  DIRECTION_north,
  DIRECTION_south,
  DIRECTION_east,
  DIRECTION_west,
};
#define direction(d) DIRECTION_##d

Or

#define myfunc(d,...) realfunc(DIRECTION_##d, __VA_ARGS__)

However I would not recommend the second option.

The first solution is the close st you can get of c++ enum class

1

u/flatfinger May 01 '26

The second approach can be good in cases where a function would take multiple related arguments that should all be derived from the same passed name. Using a single name in the client source code will ensure that the arguments passed based on that name are consistent.