rolando.cl

Conditional assignment on C

So, I’m used to ruby, and a good thing that I love is that conditionals also return values:

1
2
3
4
5
a = if test_condition
"test is true"
  else
"test is false"
end

Ok, perhaps that’s not the best example, but you get the idea. In fact, a better example might be this one:

1
a = test1 || test2 || test3 || test4

In this case, if test1 fails, test2 is executed, and so on. And it stops when the first test returns a valid true value (anything but false or nil). Nothing exciting here so far. What is cool about this, is that a will hold the value that short-circuited the conditional. In the previous example, if test1 and test2 returned nil, and test3 returned “blah”, then a would hold the value “blah”.

Let’s try the same in C (or any other variant, like Objective-C or C++):

1
2
void *obj = NULL;
obj = test1() || test2() || test3() || test4();

First, if you have the proper warnings turned on (which you should, by the way) the compiler will warn you about assigning an (int) to a (void *), second if you disregard that warning, you will end up always with a 1 or a 0 (zero) assigned to obj, which is a BAD thing :D.

The Good Way™ to do this is through a temp variable:

1
2
3
4
5
void *obj = NULL;
void *tmp = NULL;

(tmp = test1()) || (tmp = test2()) || (tmp = test3()) || (tmp = test4());
obj = tmp;

This way it will still only execute the conditions until one is met (tmp != NULL) and you will be able to rescue the value of that result.

Thanks to my friend JF for the heads up!

Post a comment


(lesstile enabled - surround code blocks with ---)