I used to call functions which returns int
error code or 0
on success like this:
int tmp = function_a() ?:
function_b() ?:
function_c();
if (tmp)
handle_error();
Now I’m working on a project which -std=c90 -Wpedantic
and I get:
warning: ISO C forbids omitting the middle term of a ?: expression [-Wpedantic]
Is there any good ISO C
approach for this? I want to avoid this:
int tmp;
tmp = function_a();
if (tmp)
handle_error();
tmp = function_b();
if (tmp)
handle_error();
And this:
int tmp;
if ((tmp = function_a()))
handle_error();
And mangling code with #define
macros.
7
While you could use a temporary variable to save the result, you’d end up with something like:
int tmp;
tmp = (tmp = function_a()) ? tmp : ((tmp = function_b()) ? tmp : function_c());
Needless to say, don’t do this. It is the equivalent of your old code, but is far less elegant. Even if it is more verbose, you should simply go with the more readable solution:
int tmp;
if(tmp = function_a()) {
handle_error(tmp);
} else if (tmp = function_b()) {
handle_error(tmp);
} else if (tmp = function_c()) {
handle_error(tmp);
}
You could also write it like this, which perhaps would be a little more straightforward:
int tmp;
if((tmp = function_a()) || (tmp = function_b()) || (tmp = function_c())) {
handle_error(tmp);
}
2