问题
I am teaching C programming and I am quite strict regarding variable declaration. As we use the C11 standard and knowing that the students would later use other programming language, I teach this rule:
Any declared symbol should have its scope as narrow as possible.
(a better phrasing would be appreciated)
In other words, a variable should be declared as late as possible to reduce its visibility from others.
This rule has several advantages:
- It often increases readability
- It forces the programmer to not reuse symbols for other purposes (global
tmp
variable) - It eases any refactoring by minimizing the diff on a fix
- It is then easier to switch to other languages
My question is: is there any strong rationale other than preserving the compatibility with C89 for declaring all variables at the top of a function block?
I would say that 70% of the books / exercises / examples found on the internet still use this C89 habit so some students always question this rule.
来源:https://stackoverflow.com/questions/65749619/rationale-for-declaring-variables-at-the-top-of-each-block-in-c