Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a programming language need keywords?

For example (in C):

int break = 1; int for = 2; 

Why will the compiler have any problems at all in deducing that break and for are variables here?


So, we need keywords because

  • we want the programs to be readable
  • we do not want to over-complicate the job of already complex compilers of today
  • but most importantly, a language is lot more powerful if some 'key'words are reserved for some special actions. Then, the language can think of being useful at a higher level rather than dying in trying to implement a for loop in an unambiguous way.
like image 304
Lazer Avatar asked Mar 16 '10 05:03

Lazer


People also ask

Why keywords is important in programming language?

but most importantly, a language is lot more powerful if some 'key'words are reserved for some special actions. Then, the language can think of being useful at a higher level rather than dying in trying to implement a for loop in an unambiguous way.


2 Answers

It's not necessary -- Fortran didn't reserve any words, so things like:

if if .eq. then then if = else else then = if endif 

are complete legal. This not only makes the language hard for the compiler to parse, but often almost impossible for a person to read or spot errors. for example, consider classic Fortran (say, up through Fortran 77 -- I haven't used it recently, but at least hope they've fixed a few things like this in more recent standards). A Fortran DO loop looks like this:

DO 10 I = 1,10 

Without them being side-by-side, you can probably see how you'd miss how this was different:

DO 10 I = 1.10 

Unfortunately, the latter isn't a DO loop at all -- it's a simple assignment of the value 1.10 to a variable named DO 10 I (yes, it also allows spaces in a name). Since Fortran also supports implicit (undeclared) variables, this is (or was) all perfectly legal, and some compilers would even accept it without a warning!

like image 94
Jerry Coffin Avatar answered Sep 28 '22 02:09

Jerry Coffin


Then what will the computer do when it comes across a statement like:

while(1) {   ...   if (condition)     break; } 

Should it actually break? Or should it treat it as 1;?

The language would become ambiguous in certain cases, or you'd have to create a very smart parser that can infer subtle syntax, and that's just unnecessary extra work.

like image 35
Kache Avatar answered Sep 28 '22 01:09

Kache