Why can an identifier not start with a number?

前端 未结 7 1797
[愿得一人]
[愿得一人] 2020-12-06 16:52

Why in java (I dont know any other programming languages) can an identifier not start with a number and why are the following declarations also not allowed?

         


        
7条回答
  •  隐瞒了意图╮
    2020-12-06 17:44

    Generally you put that kind of limitation in for two reasons:

    1. It's a pain to parse electronically.
    2. It's a pain for humans to parse.

    Consider the following code snippet:

    int d, -d;
    d = 3;
    -d = 2;
    d = -d;
    

    If -d is a legal identifier, then which value does d have at the end? -3 or 2? It's ambiguous.

    Also consider:

    int 2e10f, f;
    2e10f = 20;
    f = 2e10f;
    

    What value does f have at the end? This is also ambiguous.

    Also, it's a pain to read either way. If someone declares 2ex10, is that a typo for two million or a variable name?

    Making sure that identifiers start with letters means that the only language items they can conflict with are reserved keywords.

提交回复
热议问题