The C/C++ ternary operator is great:
int x = (someFlag) ? -1 : 1;
Delphi has a nice feature where preprocessor directives can be written on one line. Two examples:
x := {$IFDEF DBG_MY_SYMBOL} -1 {$ELSE} 1 {$ENDIF};
x := {$IF Defined(DBG_MY_SYMBOL)} -1 {$ELSEIF Defined(ANOTHER_SYMBOL)} 1 {$IFEND};
Beautiful!
Does C/C++ have a one-line equivalent like Delphi?
Does C/C++ have a one-line equivalent like Delphi?
Unfortunately, no. A C/C++ preprocessor directive is takes up a whole line by itself, so there is no direct equivalent in C/C++ to your Delphi example.
However, in C/C++, expressions can span multiple lines, so you can do something like this instead:
x =
#ifdef DBG_MY_SYMBOL
-1
#else
1
#endif
;
Or:
x =
#if defined(DBG_MY_SYMBOL)
-1
#elif defined(ANOTHER_SYMBOL)
1
#endif
;
That being said, you should consider using a separate constant for better readability, eg:
#ifdef DBG_MY_SYMBOL
const int MyConstant = -1;
#else
const int MyConstant = 1;
#endif
x = MyConstant;
Or:
#if defined(DBG_MY_SYMBOL)
const int MyConstant = -1;
#elif defined(ANOTHER_SYMBOL)
const int MyConstant = 1;
#endif
x = MyConstant;