enum c++

Started by
4 comments, last by Calin 14 years, 8 months ago
enum a1 { A =1, B }; enum a2 { C =1, D }; Can I use A and C interchangebly? Hello(enum a1); Would the compiler start complaining at Hello(C)

My project`s facebook page is “DreamLand Page”

Advertisement
No you can't use them interchangebly like so. Yes the compiler will complain because C is not part of enum a1. But, as always, there is a way around this ... which you should not take by the way.

enum a1 { A = 1, B };enum a2 { C = 1, D };void myFunction1(a1 value);void myFunction2(int value);int main(){   myFunction(C); // does not even compile   m<Function2((int)(C)); // does compile and work as expected (if you expect to have same results for A and C) but is ugly   return 0;}


PS: Is refues to mention that you could have a brute force cast to cast type a2 to type a1 because. Its ugly enough to make ints from an enum and if you encounter a code line where you want to do so it is most likely you suffered from bad overall code design and should redesign this particulay code leading to this scenario.
------------------------------------I always enjoy being rated up by you ...
I have to ask... why did you ask this question? It seems to me writing a test program to find out for yourself would have taken no more than 30 seconds...
Quote:I have to ask... why did you ask this question? It seems to me writing a test program to find out for yourself would have taken no more than 30 seconds


Usually the error descriptions the compiler is bringing up are stupid/don't help much when you're learning stuff. (I don't what to find out only if this compiles or not [which I could have figured out myself], I also want to know why it does/doesn't compile)

My project`s facebook page is “DreamLand Page”

Quote:Original post by Calin
Quote:I have to ask... why did you ask this question? It seems to me writing a test program to find out for yourself would have taken no more than 30 seconds


Usually the error descriptions the compiler is bringing up are stupid/don't help much when you're learning stuff. (I don't what to find out only if this compiles or not [which I could have figured out myself], I also want to know why it does/doesn't compile)


int main () {        enum Foo { foo };        enum Bar { bar };        Foo phoo = bar;}


error: cannot convert `main()::Bar' to `main()::Foo' in initialization


The question is, how far does your "why" range? Is the above error message enough? Do you want to know that enums in C++ are typesafe? Do you want to know that enums are defined in "ISO/IEC 14882:2003" in section 7.2, "Enumeration declarations", with Item 4 stating
Quote:Each enumeration defines a type that is different from all other types
, or do you need relevant sections about type safety and implicit conversion in C++?
phresnel & Waterwalker thanks, your posts a very insightful

My project`s facebook page is “DreamLand Page”

This topic is closed to new replies.

Advertisement