For example (in C):
int break = 1;
int for = 2;
Why will the compiler have any problems at all in deducing that break
and fo
As others said, this makes compiler parsing your source code easier. But I would like to say a bit more: it can also make your source code more readable; consider this example:
if (if > 0) then then = 10 end if
The second "if" and the second "then" are variables, while others are not. I think this kind of code is not readable. :)
If we are speaking of C++ - it already has very complicated grammar. Allowing to use keywords as variable names, for example, will make it even more complicated.
In many cases, it would be possible for the compiler to interprete keywords as normal identifiers, like in your example:
int break = 1;
int for = 2;
As a matter of fact, I just wrote a compiler for a simple assembly-like toy language which does this, but warns the user in such cases.
But sometimes the syntax is defined in a way that keywords and identifiers are ambiguous:
int break;
while(...)
{
break; // <-- treat this as expression or statement?
}
And the most obvious reason is that editors will emphasize keywords so that the code is more readable for humans. Allowing keywords to be treated as identifiers would make code highlighting harder, and would also lead to bad readability of your code.
Depending on the language definition a compiler may or may not need keywords. When it does not know what to do it can try to apply precedence rules or just fail.
An example:
void return(int i){printf("%d",i);}
public int foo(int a)
{
if(a > 2)return (a+1)*2;
return a + 3;
}
What happens if a is greater than 2?
You can define a language which dosn't use keywords. You can even define a language which alowes you to replace all symbols (since they are only very short keywords themselfes).
The problem is not the compiler, if your specification is complete and error free it will work. The problem is PEBCAD, programs using this feature of the language will be hard to read as you have to keep track of the symbol definitions.
several reasons:
The keywords may seem unambiguous in your samples. But that is not the only place you would use the variable 'break' or the variable 'for'.
writing the parser would be much harder and error prone for little gain.
using a keyword as a function or procedure name in a library may have undesired, possibly security relevant, side effects.
Because we want to keep what little sanity points we've got:
void myfunction(bool) { .. };
funcp while = &myfunction;
while(true);