Home > Blockchain >  returning failure code as enum in C seems to make code verbose
returning failure code as enum in C seems to make code verbose

Time:10-09

I'm used to old-school programming whereby functions return 0 for success, non-zero for error, and can be tested easily with

if ( ! myobject.mymethod() ) {
    handle error
}

So I'm using C 17 for the moment (though I could move forward or back) and chose to make a large number of methods return an enumeration.

So now the compiler complains there's no ! operator. Fair enough. But what is standard practice to avoid having people type:

if ( myobject.mymethod() != ReturnCode::Success ) {
    handle error
}

which makes code harder to read and write, I think, increasing total cost of ownership (TCO)?

Just some things I'm considering:

  1. define an operator!(bool) for all such enums I write in my career going forward. But I don't recall ever seeing this in other code.

  2. use preprocessor definitions of int's instead, and return those (though there's a cost in not being able to understand error 5, say, in the debugger, and having to search headers to see what 5 means

  3. exceptions are too big a solution for my needs though I've considered that

CodePudding user response:

If you use simple enum use 0 as Success then you can write code as following:

if(!functionCall())
   error handling

Or you can read about std::error_code, it has bool operator

CodePudding user response:

I would argue that

if ( myobject.mymethod() != ReturnCode::Success ) {
    handle error
}

is much clearer and less error-prone code than

if ( ! myobject.mymethod() ) {
    handle error
}

In the former, it is clear from reading this code that the block is handling the non-successful case.

In the latter, you have no idea whether the block is handling success or error or something else, and it is easy for programmers to mix this up.

You actually prove this yourself, you write that returning 0(false) is success, but your code is treating this as failure.

So don't be afraid of more verbose code, as this helps you avoid errors like this.

CodePudding user response:

Change enum class to enum to allow automatic (implicit) conversion to integers, which in turn can be used as boolean values without further work.

Values of unscoped enumeration type are implicitly-convertible to integral types.

This unscoped enumeration type is what you get by defining the enumeration with enum.

Instead, I was using the scoped enumeration time, by defining the enumeration using enum class.

https://en.cppreference.com/w/cpp/language/enum

  • Related