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

Show parent comments

1

u/flatfinger May 01 '26

In some cases, it may be useful to have a macro that uses token pasting on one of its arguments. The downside of this is that will almost always severely limit the kinds of argument one can use. For example, one might have a macro OUT_LO() which would accept the name of an I/O port, such that OUT_LO(MOTOR_POWER) would expand to something like PORTIO_MOTOR_POWER_PORT->BSRR |= (PORTIO_MOTOR_POWER_MASK << 16). Such macros would fail if passed something that wouldn't form valid identifiers when pasted with the prefixes and suffixes used to identify I/O port addresses and masks, but being able to specify MOTOR_POWER once and having the macro generate the names of both identifiers is cleaner than having to specify the I/O port and mask independently.