user3817250
user3817250

Reputation: 1043

c bitwise combination parameter of enum type

I'm trying to write a function that will accept a bitwise combination of my enum constants.

typedef enum {
    one = 1 << 0,
    two = 1 << 1,
    three = 1 << 2
} num;

void myFunc(num nums) {
    printf("%x", nums);
}

The idea being that there is a little bit of a type check (although not-enforced) on my function parameter.

myFunc will happily be called with any of the following

myFunc(one);
myFunc(two | three);
myFunc(3);

Basically the nums parameter type doesn't enforce anything. (I do get a "enumerated type mixed with another type" warning though)

So my question is, what is the c standard way for doing this kind of bitwise combination parameter? Is there any way I can make the compiler understand I want nums?

Unfortunately searching for this topic only leads me to the c# solution to this (flagsattribute). In hindsight 'c' might not have been a very good name choice.

Since this compiles, I'd much rather do it this way than myFunc(int nums); which doesn't give the compiler OR programmer any indication that it's expecting a combination of enum nums.

Creating a second enum, that holds all combinations of nums seems like overkill.

Upvotes: 1

Views: 438

Answers (2)

John Hascall
John Hascall

Reputation: 9416

As previously explained there is no compile-time way to do this in C. You could, (and should), however, add run-time checks to myFunc() to be sure that the input is acceptable.

Upvotes: 0

robbrit
robbrit

Reputation: 17960

What you're trying to do is not possible with standard C. According to C99, anything that is of type enum is actually of type int - there is no difference between the two. The purpose of an enum is pretty much just a way to present to other programmers your intentions.

Reference: http://c0x.coding-guidelines.com/6.4.4.3.html

If gcc is giving you warnings you can use the -Werror flag, downside is that all your warnings will be classified as errors in that case.

Upvotes: 1

Related Questions