In JavaScript, an expression like this 0 || "Hello World"
returns "Hello World"
.
But in C, however, it is 1
. The OR operator returns an int, instead of the actual value. I need the value to be returned instead.
How can I get the value instead of a boolean ?
I don't wanna write if else stuff with some scary declarations while dealing with logical snakes like this foo() || bar() || tar() || mar() || far()
. Well if that is the only solution then I'm gonna jump back to VBA or VimScript to rewrite the compiler from scratch so it supports that feature. Or just gonna write binary values directly to the CPU, I don't care.
I tried in this code below, but getting an error
test.c:16:16: warning: return makes pointer from integer without a cast [-Wint-conversion]
Here is where the error occurs, because the functino expect a pointer but the OR operator returns an integer.
return foo() || bee();
#include <stdio.h>
#include <stdlib.h>
char* foo()
{
return NULL;
}
char* bee()
{
return "I don't like you, short guy!";
}
char* choice()
{
return foo() || bee();
}
int main()
{
char* result = choice();
if(result == NULL) {
printf("GOt a null again");
return 1;
}
printf("Horray! Succsex!");
return 0;
}
Use an auxiliary variable:
char *res = NULL;
(res = foo()) || (res = bar()) || (res = tar()) || ...;
return res;
Note that assignment operator is used when one would expect a equality operator. The extra parentheses are used to silence warnings about using =
is the condition.
Assuming that you use GCC or CLANG compiler you can use following extension. This let's you use the value of condition as a return value of conditional operator by omitting operator's second argument:
char* choice()
{
return foo() ?: bee(); // add ?: tar() ?: mar() ?: ...
}
It's pretty much exactly what you are looking for.