K & R C Variable Names

  • A+
Category:Languages

I have some confusion for contents about variable names in K & R C. Original text as below:

At least the first 31 characters of an internal name are significant. For function names and external variables, the number may be less than 31, because external names may be used by assemblers and loaders over which the language has no control. For external names, the standard guarantees uniqueness only for 6 characters and a single case. Keywords like if, else, int, float, etc., are reserved: you can't use them as variable names. They must be in lower case. It's wise to choose variable names that are related to the purpose of the variable, and that are unlikely to get mixed up typographically. We tend to use short names for local variables, especially loop indices, and longer names for external variables.

What confused me was the external names, the standard guarantees uniqueness only for 6 characters and a single case. Does it means that for external names, only the 6 leading chars are valid and remaining chars are all ignored? For example, we defined two external variable myexvar1 and myexvar2, the compiler will treat these two variables as one? If this is true, why they advise us to use longer names for external variables?

 


Does it means that for external names, only the 6 leading chars are valid and remaining chars are all ignored? For example, we defined two external variable myexvar1 and myexvar2, the compiler will treat these two variables as one?

Yes this was true in 1990. Or rather, 6 unique leading characters of external identifiers was what the C90 standard set as minimum limit for a compiler. This was of course madness - which is why this limit was increased to 31 in C99.

In practice, most C90 compilers had at least 31 unique characters for internal and external identifiers both.


If this is true, why they advise us to use longer names for external variables?

Not sure if they advise it. But the coding style used in K&R is often plain horrible, so it is definitely not a book you should consult for coding style advise.


In modern C, it is required (C17 5.2.4.1) that we have:

63 significant initial characters in an internal identifier or a macro name

31 significant initial characters in an external identifier

So don't worry too much about which limitations the dinosaurs faced, but follow modern standard C.

As pointed out in another answer, even the restriction of 31 significant initial characters for external identifiers is listed as obsolete, meaning this might get increased even further, to 255, in future standards.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: