Naming convention - underscore in C++ and C# variables

前端 未结 19 2294
春和景丽
春和景丽 2020-11-28 01:11

It\'s common to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming conventions?

19条回答
  •  隐瞒了意图╮
    2020-11-28 01:43

    As far as the C and C++ languages are concerned there is no special meaning to an underscore in the name (beginning, middle or end). It's just a valid variable name character. The "conventions" come from coding practices within a coding community.

    As already indicated by various examples above, _ in the beginning may mean private or protected members of a class in C++.

    Let me just give some history that may be fun trivia. In UNIX if you have a core C library function and a kernel back-end where you want to expose the kernel function to user space as well the _ is stuck in front of the function stub that calls the kernel function directly without doing anything else. The most famous and familiar example of this is exit() vs _exit() under BSD and SysV type kernels: There, exit() does user-space stuff before calling the kernel's exit service, whereas _exit just maps to the kernel's exit service.

    So _ was used for "local" stuff in this case local being machine-local. Typically _functions() were not portable. In that you should not expect same behaviour across various platforms.

    Now as for _ in variable names, such as

    int _foo;

    Well psychologically, an _ is an odd thing to have to type in the beginning. So if you want to create a variable name that would have a lesser chance of a clash with something else, ESPECIALLY when dealing with pre-processor substitutions you want consider uses of _.

    My basic advice would be to always follow the convention of your coding community, so that you can collaborate more effectively.

提交回复
热议问题