Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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;
like image 337
user1041588 Avatar asked Nov 11 '11 11:11

user1041588


People also ask

Why we use underscore in variable names?

The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.

Why underscore is used in C?

It's just an identifier, it's valid. You can use _ by itself as an identifier. that makes _ a variable of type int .

Can underscore be used in a variable name in C?

Rules for naming a variable A variable name can only have letters (both uppercase and lowercase letters), digits and underscore. The first letter of a variable should be either a letter or an underscore. There is no rule on how long a variable name (identifier) can be.

What does underscore after variable name mean?

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.


2 Answers

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.)

like image 86
Kerrek SB Avatar answered Oct 04 '22 16:10

Kerrek SB


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.

like image 30
Blagovest Buyukliev Avatar answered Oct 04 '22 14:10

Blagovest Buyukliev