Search code examples
coperatorsargc

Explain an C expression with ? : and >


Could anyone kindly explain me the use of a following expression in C?

double irate = argc > 1? atof(arg[1]) : 1;
double orate = argc > 2? atof(arg[2]) : 2;

(Taken from the beginning of an soxr example https://sourceforge.net/p/soxr/code/ci/master/tree/examples/1-single-block.c.)

Does it mean something like:

"if number of arguments is bigger than one, take the first argument and place it into the irate variable, otherwise put number 1 into the same variable"?

Similarly with the second possible argument...

atof() is just a libc conversion of a string (arguments are always treated as strings in Unix/Linux) to double, error (while conversion) handling is not provided.

Am I right?


Solution

  • double irate = argc > 1? atof(arg[1]) : 1;
    

    Can be written as:

    if (argc > 1)
        irate = atof(arg[1]);
    else
        irate = 1
    

    Or can be read as: if the argument count is greater than one, convert the second argument from an ascii string to a float and store it in the variable irate, otherwise set it to the value of 1.

    Same for the second line.

    Have a look at Conditional operator