C++ enum question

Status
Not open for further replies.
Lets say I have a variable defined as type "enum". The enum has three options, option_A, option_B, or option_C. Now if I set my variable to option_A:

Code:
myVariable = option_A;

it's basically getting set to the value 0, right? (and 1 for option_B and 2 for option_C).

So can I just set the variable to 0, 1, or 2 instead?

Code:
myVariable = 0; // ??? Does this work ?

Thanks for your help.

-Proffy
 

Screndib

Ars Tribunus Militum
2,038
You can't really have a variable of type 'enum', just as you can't have a variable of type 'struct'. What you might do is make an enum like so:

Code:
enum SomeEnum
{
    Option_A,
    Option_B,
    Option_C
};

Then create a variable of type 'SomeEnum' by doing:

Code:
SomeEnum MyVariable;


Now back to your question, yes you could (though you might need to cast the number to SomeEnum) just assign the value of 0 to it and it would be exactly as if you assigned Option_A. This is generally not a good thing though as it somewhat destroys the point of making it an enum in the first place. Why is it that you want to do this? (cause there's probably a better way)
 
Originally posted by Screndib:
You can't really have a variable of type 'enum', just as you can't have a variable of type 'struct'. What you might do is make an enum like so:
Code:
enum SomeEnum
{
    Option_A,
    Option_B,
    Option_C
};
Then create a variable of type 'SomeEnum' by doing:
Code:
SomeEnum MyVariable;
Yes, that's what I meant. Should have taken more time to explain what I was doing.
yes you could (though you might need to cast the number to SomeEnum) just assign the value of 0 to it and it would be exactly as if you assigned Option_A.
Ahhh, yes, type casting. Good idea, I'll see if it compiles! :)
Why is it that you want to do this? (cause there's probably a better way)
I'm testing some APIs and want to see what happens when I set a variable outside it's enum range. Like setting it to -5 or 999999. Just basic parameter tests.

-Proffy
 
If often use a zero, 0, to denote success and a negative value to denote failure. This is in IMO a lot more flexible than using a simple boolean value of either success or failure. Ex.

Code:
boolean_t some_func(...);

if(some_func(...) != TRUE) {
  ...
  /*
  something went wrong but I don't know what 
  since I got a simple truth value
  */ 
  ...
} 

/*
or this
*/

status_t some_func(...);

status_t ret = some_func(...);

switch(ret) {
  case ERROR1:
    ...
   
  case ERROR2:
    ...  
  
  case OK:
  default:
}

/* or if don't care */

if(some_func(...) != 0) {
}

And also, this gives the option of returning a numerical value as in read/write calls too.

// tiny
 

petrov

Ars Tribunus Militum
2,714
Originally posted by _tiny_:
/*
something went wrong but I don't know what
since I got a simple truth value
*/

hopefully if your functions are properly engineered, they will set errno, or SetLastError() or something similar so you will know exactly what went wrong and you can still use the intuitive function() == TRUE for success.

--sam
 
Sorry petrov but global and sometimes even thread local errnos are evil. Avoid, avoid, avoid.

It's jumping through hoops to provide something really simple like an non boolean completion status. Having a statefull integer with no apparent relationship with the current context is not a good thing. The semantics of most programming languages cannot convey such a relationship so you have to rely on documentation. Never rely on documentation.

Yes you can use exceptions for this sometimes but not always, for instance when using a non-blocking read call on a file descriptor. I for one would not enjoy it if an exception was thrown if the operation would block.

Or like people say "exceptions are for exceptional events" but sometimes that line isn't all that clear. You can argue against the kind of "fascist" approach that forces you to accept some other bozos judgement as to what is a "exceptional event" in your program.

// tiny
 
Originally posted by PeterB:
NO!

Exceptions are for the exceptional -- things like "holy fuck, I ran out of memory". Not for simple return values.
What constitutes exceptional is somewhat up to interpretation. The standard library will throw exceptions for (some) violations of a method's preconditions for example.

I'd say, if there is an error encountered or a precondition violated that prevents the function or method from doing what it's meant to be doing, then there's a good case for throwing an exception. Other error handling options though are of course available.

Originally posted by FireJade:
I use enums a lot, but for some reason I dont like boolean variables. If I need to test if something is true or false I just use 0s and 1s
Just be careful ... C (as you know!) treats 0 as false and non-zero as true, so explicitly testing a result for equality with 1 can be dangerous. There's nothing quite so awful as finding in code the construction
Code:
/* bad code, no biscuit */
#define FALSE 0
#define TRUE 1

...

if (some_fn()==TRUE) { ... }

...

int some_fn() {
   ...
   return failed_flag?0:num_found;
}
 
Or like people say "exceptions are for exceptional events" but sometimes that line isn't all that clear. You can argue against the kind of "fascist" approach that forces you to accept some other bozos judgement as to what is a "exceptional event" in your program.
Stuff that is predictable but not going to occur during the normal execution of a program. For instance, specifying a bad filename is non-exceptional (files get deleted, users mistype them, and so on). Running out of memory (assuming a typical VM OS), OTOH, is something that should never happen.
 
Originally posted by euzeka:
Anything you don't expect is exceptionnal.
The language provides no facility for handling such situations.

Exceptions and return values can only deal with things that you expect to occur. They don't provide a capability to handle the unexpected.

The difference is the conditions under which you expect things to occur, not whether you expect them to occur or not.

Anything you do expect probably deserves better handling than a simple return value.
Er, why? If a return value says "file not found", what more do you need to do? Return values are low overhead, easy to use, and designed precisely for this kind of information.
 

bigdruid

Ars Scholae Palatinae
731
I'm a big fan of exceptions - having coded in lots of non-OO languages (C, x86 asm) and a few OO languages (C++, Java) I can tell you that my code is infinitely cleaner with exceptions than without them.

Reasons?

1) All the languages I ever use allow for *one* return value from a function. Consider the following:

File f = new File("foo");
int i = f.getSize();

How do you handle the case where the file foo doesn't exist? In C, you'd return "-1" from getSize(), but then you can't readily differentiate between non-existent files, permission errors, I/O errors, etc etc etc. Maybe you'd pass in an "error value" that could then be modified, but pass-by-reference values are gross in your APIs, especially for values that aren't typically used anyway.

int size = f.getSize(&err);

2) With exceptions, it's easy to enclose many statements in a single try/catch block, and handle errors for all of them in the same place

With error codes, you end up doing if/then clauses after every statement, checking for error status.

3) In general, integers suck, and not just for error codes

Integers are great for numbers, and not much else, and *certainly* not error codes. They aren't typesafe *at all*. Over the years I've been coding, if I had $10 for every time I've tracked down a bug that was due to someone mis-interpreting an error code as a different type, I'd be able to take a nice vacation.

For example, let's say you write a routine called "foo()", which returns one of 3 error codes:

0 - NO_ERROR
1 - FILE_NOT_FOUND
2 - IO_ERROR

In foo, you then call another routine which has a different set of error values:

0 - NO_ERROR
1 - PATH_INVALID
2 - PERMISSION_ERROR
3 - ... etc ...

Bad things happen if you ever screw up and forget to map between the two error types - the compiler can't help you, as all ints are identical as far as it's concerned.

At least with exceptions, if you define one exception class, and throw another, the compiler will shout.

-druid "Climbing off my soapbox now"
 
You have standard error codes. Perhaps even an enumeration of error codes. You don't arbitrarily reassign a given value for each and every routine. If error 5 is access denied in one place, it's access denied in all places. So if you need to just return a value from another function, you can return it verbatim.

How do you handle the case where the file foo doesn't exist? In C, you'd return "-1" from getSize(), but then you can't readily differentiate between non-existent files, permission errors, I/O errors, etc etc etc. Maybe you'd pass in an "error value" that could then be modified, but pass-by-reference values are gross in your APIs, especially for values that aren't typically used anyway.
For that, I'd create the file, since you didn't tell it not to. The file would always exist. In general? I'd do what the standard library does, which is to have a mechanism for determining if an operation has failed. If a method is invoked on a failed file, do something appropriate. Perhaps just return some harmless default values (like a zero size).

With exceptions, it's easy to enclose many statements in a single try/catch block, and handle errors for all of them in the same place

With error codes, you end up doing if/then clauses after every statement, checking for error status.
On the contrary.

If you have exceptions and want to be able to handle errors all along the way, you need to do the same thing -- wrap each statement with a <tt>try</tt>/<tt>catch</tt> block. C++ exceptions aren't resumable -- if you want to be able to handle individual errors, you need to wrap individual statements. Further, you'll either need to have a different exception for each different error, or have a similar set of if/else clauses to determine what to do with the error.

[This message was edited by PeterB on April 25, 2002 at 21:24.]
 
PeterB wrote:
You have standard error codes. Perhaps even an enumeration of error codes. You don't arbitrarily reassign a given value for each and every routine. If error 5 is access denied in one place, it's access denied in all places. So if you need to just return a value from another function, you can return it verbatim.

That's the ideal, but it becomes a real hassle when you're incorporating code that has been developed elsewhere which has adopted a different standard. One can write little error code conversion tables, which never work quite right because the domains covered by the different codes never quite match perfectly. It's just ... awful! Yuck! I've been there :(

Still, in a self-contained or smallish project, error codes can be manageable. Class-based exceptions though are often more easily maintained. In C++, there's often a sensible standard exception that you can derive from or just throw directly.
 
Originally posted by HalfFlat:
That's the ideal, but it becomes a real hassle when you're incorporating code that has been developed elsewhere which has adopted a different standard. One can write little error code conversion tables, which never work quite right because the domains covered by the different codes never quite match perfectly. It's just ... awful! Yuck! I've been there :(
This is why we have errno.h, and similar lists of standard (either to an OS or to a language) error codes. Only if our error is completely impossible to describe using the standard codes do we consider using our own value.

Still, in a self-contained or smallish project, error codes can be manageable. Class-based exceptions though are often more easily maintained. In C++, there's often a sensible standard exception that you can derive from or just throw directly.
Exceptions are for a *different* job to return values. For many tasks, exceptions are harder to use, slower, and hide what you're trying to do with an excess of typing.
 

bigdruid

Ars Scholae Palatinae
731
Originally posted by PeterB:
This is why we have errno.h, and similar lists of standard (either to an OS or to a language) error codes. Only if our error is completely impossible to describe using the standard codes do we consider using our own value.
Again, the problem comes in when integrating with code you didn't write. Adhering to some mythical universal list of error codes is nice in theory, but I have to wonder how well it really holds up in practice (how many RMI error codes are in "errno.h"? SQL errors? TCPIP/Socket errors? DNS errors? etc etc etc). And even if errno.h supports all of these, you still have to rely on every library you use to also use them.

And if some piece of code in the system *doesn't* adhere to your standard, don't expect the compiler to bail you out, because ints are ints, my friend.

Exceptions are for a *different* job to return values. For many tasks, exceptions are harder to use, slower, and hide what you're trying to do with an excess of typing.

Well, for every case I can think of that exceptions work better for, I'm sure you can find a corresponding case where error codes are more appropriate (e.g. status checking routines, routines where you generally want to ignore errors, like File.close(), etc).

Nevertheless, my experience is that when used appropriately (but not necessarily universally), exceptions yield better, more maintainable error handling code, for many of the reasons I outlined previously.
 
I fail to see it being any easier integrating code that throws exceptions rather than returning error codes. Both will still require a change in the source code since you have to different groups of exceptions and different error codes. The difference is that the error code only propagates to the caller of the function whereas an exception will follow through the entire call stack.

I must agree with PeterB here, exceptions are the most usefull as a replacement for the exit()/atexit()/longjmp() calls. Errors best to die/restart at and handle those kinds of things gracefully. I myself rarely use or promote the use of exceptions in C++. Come to think of it I rarely promote the use of C++ :D .

// tiny
 
Originally posted by bigdruid:
Again, the problem comes in when integrating with code you didn't write. Adhering to some mythical universal list of error codes is nice in theory, but I have to wonder how well it really holds up in practice (how many RMI error codes are in "errno.h"? SQL errors? TCPIP/Socket errors? DNS errors? etc etc etc). And even if errno.h supports all of these, you still have to rely on every library you use to also use them.
And you have to rely on every library you use to throw a decent set of exceptions at reasonable places... exceptions don't solve this problem.

And if some piece of code in the system *doesn't* adhere to your standard, don't expect the compiler to bail you out, because ints are ints, my friend.
Given the scarcity of exception specifications (and that they're arguably Bad Things anyway), the same is perfectly possible of exceptions -- someone can throw something you can't handle. Sure, you can put in a <tt>catch(...)</tt> block, but there's not a great deal you can do that's intelligent in such a block, because you don't know who's thrown or why.
 
Exceptions are not a panacea; they will of course not magically write their own error handlers. However, they do avoid the problem of overlapping integer error codes, and they'll bring the compiler on-side to help catch errors. Like type-safety, exception classes provide a level of checking and protection for the programmer, allowing programmer errors to be discovered more easily and such.

There are other advantages of exceptions too of course, which I'm sure you all are familiar with. There are situations where an error expressed as a return value can be cleaner or more desirable, but just as validly, the use of a try and catch block can simplify a lot of the normal error handling code, which in turn makes it easier to write correct code.

Certainly there is scope for using them outside the end of the world scenarios discussed above.
 
Status
Not open for further replies.