Eric Brotto
Eric Brotto

Reputation: 54281

What does the question mark character ('?') mean?

What does a question mark (?) in C mean?

Upvotes: 15

Views: 51256

Answers (8)

Didier Trosset
Didier Trosset

Reputation: 37477

? is the first symbol of the ?: conditional operator.

a = (b==0) ? 1 : 0;

a will have the value 1 if b is equal to 0, and 0 otherwise.

Upvotes: 29

Benoit
Benoit

Reputation: 79233

Additionally to other answers, ? can be part of a trigraph.

Upvotes: 13

bpm
bpm

Reputation: 105

Most likely the '?' is the ternary operator. Its grammar is:

RESULT = (COND) ? (STATEMEN IF TRUE) : (STATEMENT IF FALSE)

It is a nice shorthand for the typical if-else statement:

if (COND) {
    RESULT = (STATEMENT IF TRUE);
} else {
    RESULT = (STATEMENT IF FALSE);

as it can usually fit on one line and can improve readability.

Some answers here refer to a trigraph, which is relevant to the C preprocessor. Take a look at this really dumb program, trigraphs.c:

# /* preprocessor will remove single hash symbols and this comment */
int main()
{
    char *t = "??=";
    char *p = "??/"";
    char *s = "??'";
    ??(, ??), ??! ??<, ??>, ??-
    return 0;
}

invoking only the c preprocessor by running gcc -E -trigraphs trigraph.c the output is

int main()
{
 char *t = "#"
 char *p = "\"";
 char *s = "^";
 [, ], | {, }, ~
 return 0;
}

Hopefully that clarifies a little bit what a trigraphs are, and what a '?' "means" in C.

Upvotes: 1

Javed Akram
Javed Akram

Reputation: 15354

This is a ternary Operator which is conditional operator uses like if-else

example

int i=1;
int j=2;
int k;
k= i > j ? i : j;
//which is same as
if(i>j)
  k=i;
else
  k=j;

Usage: Syntax of ?: is

assignment_Variable = Condition ? value_if_true : value_if_false;

Upvotes: 11

Stefan Papp
Stefan Papp

Reputation: 2255

This is a so called conditional operator. You can shorten your if else statement with this operator.

The following link should explain everything

http://www.crasseux.com/books/ctutorial/The-question-mark-operator.html

Upvotes: 3

zoul
zoul

Reputation: 104125

That’s probably a part of the ternary operator:

const int numApples = …;
printf("I have %i apple%s.\n", numApples == 1 ? "" : "s");

Upvotes: 4

ckv
ckv

Reputation: 10838

It is a conditional operator. For example refer the below link http://en.wikipedia.org/wiki/Conditional_operator

Upvotes: 2

Related Questions