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.
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.
It's not definitively legal, but your implementation is allowed to accept it.
Consider:
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.
This is implementation defined behavior.
$
is not included in grammar for an identifiers the rules for identifier names in C++ are:But it does allow for implementation-defined characters which many compilers support as an extension, including gcc and Visual Studio.
The actual grammar is covered in the draft C++ standard section
2.11
Indentifier:We can see this applies to
define
from section16
Preprocessing directives. We can see from the grammar that it must be an identifier:There is a funny situation with some compilers that allow to use
$
in identifiers. For example at least MS VC++ 2010 allows to use$
in identifiers.So if for example you defined
and then wrote
then instead of symbol $ you will see in the console output number 1 or some integer number.:)