-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
  • 6,221
  • 16
  • 30
fox18
  • 19
  • 2
  • 1
    `"?"` is the string literal consisting of the character `?` here. What are you having trouble understanding? – muru Apr 23 '19 at 11:20
  • [?: operator](https://en.wikipedia.org/wiki/%3F:) –  Apr 23 '19 at 11:26

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
  • 4,213
  • 2
  • 17
  • 28
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
  • 106,608
  • 13
  • 126
  • 198