28

I am refactoring some very old legacy code which is full of bugs and very questionable practices, at least for modern standards. Now I ran across one line which I simply cannot decipher:

p and k are of type int *

return p??!??!k?p?*p:sizeof(*k):0;

When I saw it I could not believe my eyes - I know the ? operator, but its syntax is bool ? trueresult : falseresult and a ?? operator does neither make sense (lazy evaluation does really not apply here), not could I find a reference of that mysterious operator anywhere.

It would be really cool if someone shed some light on this matter.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2573221
  • 494
  • 4
  • 13

2 Answers2

38

It's called Trigraph:

C11(ISO/IEC 9899:201x) §5.2.1.1 Trigraph sequences

Before any other processing takes place, each occurrence of one of the following sequences of three characters (called trigraph sequences17)) is replaced with the corresponding single character.

??=    #
??(    [
??/    \
??)    ]
??'    ^
??<    {
??!    |
??>    }
??-    ~

It's also in C++11(ISO/IEC 14882:2011) § 2.3 Trigraph sequences

So after trigraph replacement, the line return p??!??!k?p?*p:sizeof(*k):0; turns into

return p || k ? p ? *p : sizeof(*k) : 0

Since the ternary operator has a rather low precedence, it's actually:

return (p || k) ? (p ? (*p) : sizeof(*k)) : 0;
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
8

That line of code is equivalent to:

return p || k? p? *p : sizeof(*k) : 0;

Or more clearly:

return (p || k)? (p? (*p) : sizeof(*k)) : 0;
user123
  • 8,970
  • 2
  • 31
  • 52