Could someone explain me what the line in the title actually does?

Am I correct

if argc is 3
    char* text is argv[2]
    char* text is argv[1]


If so, how do the operators work in this line?


Yes, you are correct.

char* text = (argc == 3) ? argv[2] : argv[1];

actually means

char* text = ((argc == 3) ? argv[2] : argv[1]);

i.e. assign some value to char *text with the help of Ternary Operator.

Ternary operators work as

some_condition ? execute_this_if_true : execute_this_if_false ;

Here, firstly, argc == 3 is evaluated. Depending on whether true or false, the next statement is executed. But the whole is used with an assignment operator(=), so the value argv[2] is assigned if test evaluates to true(argv[3] if test evaluates to false).

Same things can be done with return statements. Say, You want to design a function that returns remainder when a number is divided by 2, then you can use ternary operator as follows :

int foo(int n)
      return (n%2 == 1) ? 1 : 0 ;
  • Thanks for this! – tofanheu Oct 30 '14 at 10:06
  • @sinister cant u just use return n%2 – Aryan Jain Nov 24 '17 at 3:30
  • In that particular example I mentioned, you could do return n%2, but that wasn't the point I meant to highlight, I wanted to show that this operator can be used with return statements as it has been used with assignment operator in the question – sinister Nov 26 '17 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .