3

if I wrote like this:

typedef enum {
  foo_1,
  foo_2
}foo ;

I found that I can use

int footype = foo::foo_1 in c++

and I can directly use

int footype = foo_1 in c,

so is there a way that can write same code that works both in c++ and c? the code is inside one header file with only one structure.

3
  • Just use foo_1 without the namespace, it should work in both, althougt you have to declare using namespace foo for c++ Commented Nov 7, 2012 at 15:15
  • 3
    @h3nr1x foo is not a namespace and no need to declare it in C++. Commented Nov 7, 2012 at 15:16
  • @icepack yes, you're right, I missreaded the question and obviated the foo after the typedef, sorry Commented Nov 7, 2012 at 18:09

3 Answers 3

6
int footype = foo_1;

That will compile in both C and C++.

int footype = foo::foo_1;

This syntax is only necessary for C++11's strongly typed enums.

Sign up to request clarification or add additional context in comments.

Comments

4

This

int footype = foo::foo_1

is legal only in C++11. In C++03 an enumeration is not a scope and this is illegal, just like in C. In C++11 there are two types of enums - ordinary C-like enums, and scoped enums, declared with

 enum class

For the latter, the enumerator qualification(::) is mandatory. For the former - optional.

So, using simply

int footype foo = foo_1;

will work in all C, C++03 and C++11

1 Comment

It looks suspiciously like you didn't read the question... this is about writing code that is compatible with C and C++ (for use in header files).
1

If you are OK with dropping the typedef it should "just work"

enum {
    foo_1,
    foo_2
};

int
main(void)
{
    int foo = foo_1;

    return 0;
}

That compiles for me with both gcc and g++

g++ --std=c++03 enum.cc -o enum_cpp
gcc --std=c99 enum.c -o enum_c

2 Comments

Having the typedef there is not an issue
Make it gcc -Wall .../g++ -Wall ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.