Home > OS >  pass truthy value of two non-boolean values to a function in a more terse way
pass truthy value of two non-boolean values to a function in a more terse way

Time:08-25

My goal here is to pass the non-empty value of 2 given values (either a string or an array) to a function foo.
In Javascript I'd be able to do:

// values of variables a and b when calling foo
// a = "hello" 
// b = []
foo( a || b ) 
// passes a, since b is empty and a is not (i.e
// it contains at least 1 character)

In C however, this doesn't work since the logical operator || only works with boolean values.

I would like to know if there is a shorter alternative to:

std::vector<std::string> a; // assuming this is empty
std::string b;              // assuming this is NOT empty (contains a string value)
if (a.empty()){
    foo(b);
}else{
    foo(a);
}

CodePudding user response:

You could use ?:, but you can’t define a foo that can use it as an argument. So try

!a.empty() ? foo(a) : foo(b)

You can’t make a foo that takes either type because C is strongly-typed, not dynamic like Javascript. And auto doesn’t change that — you aren’t naming the type, but there still is one.

This also works

foo(!a.empty() ? a : std::vector<std::string>(1, b));
  • Related