Search code examples
cmacrospreprocessor

if else shorthand in C


Is the statement below a kind of shorthand? i need someone help me understand with it.

#define clean_errno()(errno == 0? "None": strerror(errno)) 

From the execution result, I guess it means once I confront clean_errno(),if errno ==0, I replace clearn_errno() with None, if not, I replace clean__errno() with strerror(errno). but I don't know how to analyse this statement logically?


Solution

  • The code is evaluated during runtime and follows the shorthand:

    condition ? if_true : if_false
    

    This shorthand is very similar to a regular if else statement.

    However, unlike normal if else in C, the shorthand can be used as an expression as well as a statement. i.e.:

    char * str = 1 ? "true" : "false";
    

    ... which doesn't work so well with if else (char * str = if ... probably wouldn't work).

    Try it with 0 ? "true" : "false" and test it out.

    Good luck!