Rationale for declaring variables at the top of each block in C? [closed]

久未见 提交于 2021-01-28 11:23:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!