1
$\begingroup$

When I started doing programming I wondered that why the variable names can't start with integer. Back then I accepted that , may be this is how the compiler designers have decided to go with. But now I am studying Compiler Design and they say that lexical analyzer produces token and it is easy / fast if we use identifiers as regular languages. So the regular expression like this : $(number)^*(underscore + alphabet)^+(number)^*$

Why they don't use this? As per compiler I don't see any ambiguity or problem in this as we have symbol table entries for each token. I know that many similar question are asked but I want to know as per lexical analysis and compiler design perspective.

$\endgroup$
1
1
$\begingroup$

In many languages, 1e3 is a literal that represents 1000, 0x10 is a literal that represents 16. If we used your proposed regexp for variable names, it would be ambiguous whether those expressions should be represented as a literal or as a variable name.

$\endgroup$
3
  • $\begingroup$ Yes , but we have symbol table which have an attribute named address that corresponds to the address of the token. So what's the problem in it. We will be having different entries for a literal a variable name. Isn't it? $\endgroup$ Jul 7 at 2:51
  • $\begingroup$ @Brijeshjoshi, the lexer usually doesn't depend on the symbol table - it would become much more complicated if it had to. I suspect the language grammar would often be ambiguous if you didn't know whether a particular expression is a literal or a variable name. $\endgroup$
    – D.W.
    Jul 7 at 5:40
  • 1
    $\begingroup$ If you rely on the symbol table, that means you can't even take a small bit of code and figure out what the components are. So I write a small program, say 20,000 lines of code, and one day I add a line of code somewhere and because of that 1e3 isn't the number 1000.0 anymore but a variable. That's a real problem. For example I add a line 1e3 = 1e4 and every 1e3 following this changes its meaning to 10000.0. $\endgroup$
    – gnasher729
    Jul 7 at 22:05
2
$\begingroup$

It's worth noting that there are some programming languages, even common ones, that support what you want. For example:

$\endgroup$
0
$\begingroup$

Many languages support unicode. For example, ①②③⑳ would be a valid Swift identifier. But being able to have the same character sequence being both an identifier and a number is at best confusing and useless.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.