Could someone explain me what the line in the title actually does?
Am I correct
if argc is 3
char* text is argv[2]
else
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 ;
}