Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you start a variable name with $ in C?

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:

Code

#include <stdio.h>

int main() {
    int myvar=13;
    int $var=42;
    printf("%d\n", myvar);
    printf("%d\n", $var);
}

Output

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?

like image 771
Jay Mody Avatar asked Sep 16 '19 01:09

Jay Mody


1 Answers

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:

  • a nondigit, which is one of underscore, “a” to “z”, or “A” to “Z”,
  • a universal-character-name, or
  • other implementation-defined characters.

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.

like image 124
Eric Postpischil Avatar answered Oct 11 '22 03:10

Eric Postpischil