I was under the impression that you could only start variable names with letters and _, however while testing around, I also found out that you can start variable names with $, like so:
#include <stdio.h>
int main() {
int myvar=13;
int $var=42;
printf("%d\n", myvar);
printf("%d\n", $var);
}
13
42
According to this resource, it says that you can't start variable names with $ in C, which is wrong (at least when compiled using my gcc version, Apple LLVM version 10.0.1 (clang-1001.0.46.4)). Other resources that I found online also seem to suggest that variables can't start with $, which is why I'm confused.
Do these articles just fail to mention this nuance, and if so, why is this a feature of C?
In the C 2018 standard, clause 6.4.2, paragraph 1 allows implementations to allow additional characters in identifiers.
It defines an identifier to be an identifier-nondigit character followed by any number of identifier-nondigit or digit characters. It defines digit to be “0“ to “9”, and it defines the identifier-nondigit characters to be:
Thus, implementations may define other characters that are allowed in identifiers.
The characters included as universal-character-name are those listed in ranges in Annex D of the C standard.
The resource you link to is wrong in several places:
Variable names in C are made up of letters (upper and lower case) and digits.
This is false; identifiers may include underscores and the above universal characters in every conforming implementation and other characters in implementations that permit them.
$ not allowed -- only letters, and _
This is incorrect. The C standard does not require an implementation to allow “$”, but it does not disallow an implementation from allowing it. “$” is allowed by some implementations and not others. It can be said not to be a part of strictly conforming C programs, but it may be a part of conforming C programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With