Function names in C++: Capitalize or not? [closed]

2019-01-21 15:48发布

What's the convention for naming functions in C++?

I come from the Java environment so I usually name something like:

myFunction(...) {
}

I've seen mixed code in C++,

myFunction(....)
MyFunction(....)
Myfunction(....)

What's the correct way?

Also, is it the same for a class method as well as a non-class method?

12条回答
Bombasti
2楼-- · 2019-01-21 16:25

The most common ones I see in production code are (in this order):

myFunctionName     // lower camel case

MyFunctionName     // upper camel case

my_function_name   // K & R ?

I find the naming convention a programmer uses in C++ code usually has something to do with their programming background.

E.g. ex-java programmers tend to use lower camel case for functions

查看更多
时光不老,我们不散
3楼-- · 2019-01-21 16:27

Since C++11, you may want to use either snake_case or camelCase for function names.

This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin and end (case-sensitive) for that class.

Consequently, using e.g. PascalCase for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.

查看更多
迷人小祖宗
4楼-- · 2019-01-21 16:27

There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.

Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.

查看更多
The star\"
5楼-- · 2019-01-21 16:32

Do as you wish, as long as your are consistent among your dev. group. every few years the conventions changes..... (remmeber nIntVAr)...

查看更多
等我变得足够好
6楼-- · 2019-01-21 16:33

As others said, there is no such thing in C++. Having said that, I tend to use the style in which the standard library is written - K & R.

Also, see the FAQ entry by Bjarne Stroustrup.

查看更多
再贱就再见
7楼-- · 2019-01-21 16:34

Most code I've seen is camelCase functions (lower case initial letter), and ProperCase/PascalCase class names, and (most usually), snake_case variables.

But, to be honest, this is all just guidance. The single most important thing is to be consistent across your code base. Pick what seems natural / works for you, and stick to it. If you're joining a project in progress, follow their standards.

查看更多
登录 后发表回答