Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cryptic line "??!??!" in legacy code [duplicate]

Tags:

c++

c

operators

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.

like image 372
user2573221 Avatar asked Jul 18 '13 08:07

user2573221


2 Answers

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;
like image 82
Yu Hao Avatar answered Nov 18 '22 07:11

Yu Hao


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;
like image 44
user123 Avatar answered Nov 18 '22 07:11

user123