-2
1:snprintf(       buf, sizeof(buf),
2:                "%s exe=%s hostname=%s addr=%s terminal=%s res=%s",
3:                message, exename,
4:                hostname ? hostname : "?",
5:                addrbuf,
6:                tty ? tty : "?",
7:                success
                );

In the above code in line number 6, what does "?" represents (not the ternary operator)

What does tty : tty : "?" mean?

ilkkachu
  • 5,940
  • 14
  • 27
fox18
  • 19
  • 2

2 Answers2

5

In line 6,

tty ? tty : "?"

the first ? is the ternary operator. The second one, in quotes, is a question mark character in a character string of length 1 (one character plus a null terminator).

So that line says that if tty is not null, use tty, otherwise use the string "?".

L. Scott Johnson
  • 3,944
  • 2
  • 15
  • 26
0

If tty is NULL, snprintf() will output the string "?" (one character) instead of causing UB if you just stick with tty.

char *tty = NULL;
printf("%s", tty); // UB
printf("%s", "?"); // print a 1-character string
printf("%s", tty?tty:"?"); // print tty's value or ?
pmg
  • 103,426
  • 11
  • 122
  • 196