Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some functions/variables have the character "_" in front of them , in C++ ? [duplicate]

Tags:

c++

I've seen quite a lot lately, in games or other applications that class data members, or methods or other stuff have "_" in front of the name. For example taken fro DXUT.cpp (Directx) _Acquires_lock_(g_cs) or _Releases_lock_(g_cs) or _tmain . There are numerous examples like this in game programming like there (Taken from GameFromScratch Tutorial)

  static GameState _gameState;
  static sf::RenderWindow _mainWindow;

These are just some data members of some type.

Is there any reason behind the _ char? Is if specifically for something?

like image 677
Sabyc90 Avatar asked Feb 07 '23 18:02

Sabyc90


2 Answers

Usually, when you see a name with leading underscore, it either

  • belongs to the (C++) implementation, or

  • has been chosen by someone unaware of the first possibility.

It's not advisable to use names with leading underscore in user code.

Any name starting with underscore is reserved to the implementation in the global namespace, and any name starting with leading underscore followed by uppercase, is reserved to the implementation anywhere.

As I recall also any name with two successive underscores, is reserved.


A novice programmer may use leading underscore to indicate “data member”.

The usual convention, for those aware of the above, is instead a trailing underscore, and/or a prefix like m or my.

E.g. trailing underscore is, as I recall, used in Boost, while an m or my prefix is used (still as I recall) in MFC.

like image 197
Cheers and hth. - Alf Avatar answered Mar 16 '23 00:03

Cheers and hth. - Alf


_Acquires_lock_(g_cs) or _Releases_lock_(g_cs)

That naming convention uses reserved names which means only the compiler implementation is allowed to use them.

That ensures that the implementation can use names which can never clash with macros or other names defined by users, because users are not allowed to use those reserved names.

The names with a single underscore followed by a lowercase letter are just idiomatic ways to denote a member variable, or a private implementation detail that is not part of the API.

like image 29
Jonathan Wakely Avatar answered Mar 16 '23 00:03

Jonathan Wakely