How to use the ternary operator this way : defined(FOO) ? value1 : value2

hello there !

I often encounter a situation in which I do :

#if defined(FOO)
myfunc(0);
#else
myfunc(1);
#endif

This is tedious, and the duplication bother me a bit. I'd like to do something like :

myfunc(defined(FOO) ? 0 : 1)

(here FOO is just a defined symbol with no specific value)

Is there a way to do it ?

thanks a lot !


I think the closest you get is something like this:

1
2
3
4
5
6
7
myfunc(
#if defined(FOO)
	0
#else
	1
#endif
);


If you are doing this in a multiple places it might be easier to define a regular C++ constant that you can simply use the ternary operator on.

1
2
3
4
5
#if defined(FOO)
const bool foo_defined = true;
#else
const bool foo_defined = false;
#endif 

 
myfunc(foo_defined ? 0 : 1);


If the ternary expression is always used to decide between these two values you might want to store the value directly as a constant instead so that you don't need to use the ternary operator at all.

1
2
3
4
5
#if defined(FOO)
const int x = 0;
#else
const int x = 1;
#endif 

 
myfunc(x);
hi Peter,
Thanks a lot for your answer!
Actually, I'm on a codebase in a team where I can't really add such modifications in the main headers of the project. I should have precised it in my message :/.
But indeed, your solution may be very useful if I add it in a local file.
I wondered if there was some preprocessor magic that allowed such a feat but I'm under the impression that the C preprocessor can't do that yet.
thanks again :)
Topic archived. No new replies allowed.