Search code examples
c++c-preprocessordollar-sign

Will using a preprocessor directive to define what a dollar sign represents cause any conflicts?


Can I use the following in C++?:

#define $ cout

int main(){
    $<<"Hello World!\n";
    return 0;
}

I'm wondering whether it will cause any conflicts.


Solution

  • It's not definitively legal, but your implementation is allowed to accept it.

    Consider:

    [C++11: 2.5/1]: Each preprocessing token that is converted to a token (2.7) shall have the lexical form of a keyword, an identifier, a literal, an operator, or a punctuator.

    Here, your $ is obviously not a keyword, operator or punctuator (as these are enumerated in the standard), and it doesn't look like a literal, so it could only be an identifier; now, identifiers must contain only alphanumerics and underscores, and digits cannot be leading (based on the grammar denoted under [C++11: 2.11]).

    However, the standard does also allow implementations to accept other characters, so what you want to do may work, but it will not be portable.