Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question mark operator in expressions [duplicate]

Tags:

K&R Second Edition (page 71)-- I must have missed the explanation:

sign = (s[i] == '-') ? -1 : 1;

The context of this is a function that converts a string to a double. This part in particular comes after the function skips white space. I infer it is checking for positive or negative value, and saving it as either -1 or +1 for sign conversion at the end of the function... return sign * val /power;

I would like to do better than infer... I'm particularly unsure of what the ? and : 1 are doing here (or anywhere, for that matter).

It kind of seems like an abstract if statement. Where ? checks for truth and : is else... is that so? Is it limited to if/else?

I am a beginner and I haven't come across this expression syntax before, so I am wondering if there is a particular reason it seems to often be replaced by a formal if/else--besides, perhaps, readability?