What is the reason for underscore in C variable name definition?

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

I am trying to understand when a developer needs to define a C variable with preceding '_'. What is the reason for it?

For example:

uint32_t __xyz_ = 0; 

回答1:

Maybe this helps, from C99, 7.1.3 ("Reserved Identifiers"):

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

Moral: For ordinary user code, it's probably best not to start identifiers with an underscore.

(On a related note, I think you should also stay clear from naming types with a trailing _t, which is reserved for standard types.)



回答2:

It is a trick used in the header files of C implementations for global symbols, in order to prevent eventual conflicts with other symbols defined by the user.

Since C lacks a namespace feature, this is a rudimentary approach to avoid name collisions with the user.

Declaring such symbols in your own header and source files is not encouraged because it can introduce naming conflicts between your code and the C implementation. Even if that doesn't produce a conflict on your current implementation, you are still prone to strange conflicts across different/future implementations, since they are free to use other symbols prefixed with underscores.



回答3:

whether its C or not, the leading underscore provides the programmer a status indication so he does not have to go look it up. In PHP, or any object oriented language where we deal with tens of thousands of properties and methods written by 1000's of authors, seeing an underscore prefix removes the need to go dig through the class andlook up whether its declared private, or protected or public. thats an immense time saver. the practice started before C, i am sure...



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