0

In most of the programming languages variable names should begin with a letter or an underscore, followed by any combination of letters, numbers, and the under-score character. I have found this in c,c++ and php (after the $).

  1. Is it just a convention followed by compiler/interpreter writers or are there any practical reasons for this?

  2. Why is it necessary that variable names be composed only of letters,underscore and numbers in these languages?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 1
    In C++ there are a bunch of rules about when you should and should not lead with an underscore. More here: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – user4581301 Jul 16 '16 at 03:23
  • 1
    Every language have an code of conduct so welcome to C. – tryKuldeepTanwar Jul 16 '16 at 03:59
  • 1
    `if (123f == 456l) {` <-- one could be a constant numeric value, the other could be a variable name starting with a digit. How would you, let alone a compiler, be able to work out which is which? – Elias Van Ootegem Jul 16 '16 at 13:18

1 Answers1

1
  1. It would be ambiguous whether 4U is an integer or an identifier. This assumes that 4 on its own would be an invalid identifer.
  2. #include, a*a and other constructs would be ambiguous.

_ isn't used as operator and a word beginning with [A-Za-z_] in C is either a predefined keyword or an identifier. No ambiguity possible.

a3f
  • 8,517
  • 1
  • 41
  • 46
  • why is that _ is not an operator? why not ~ instead o f _ ? my question is -is it a convention followed that _ wont be used as an operator? is it derived from any of the preceding languages from which they were derived? Since there are no other answers and yours partially does answer my question, i am accepting your answer.Thanks for replying. –  Jul 16 '16 at 13:44
  • 1
    @Bitto It dates back to IBM introducing the `_` in their EBCDIC charset for use as a word-break character on punch cards. ASCII adopted it too and FORTRAN allowed it in identifiers. If your are wondering about the history behind different operators, you could ask on programmers.SE. – a3f Jul 16 '16 at 16:21