91

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?

Jarvis
  • 8,494
  • 3
  • 27
  • 58
user69514
  • 26,935
  • 59
  • 154
  • 188
  • 1
    thanks all. I'll go with myFunction() since that's what I am used to – user69514 Nov 21 '09 at 18:34
  • 1
    There is no "correct" way, it's all opinion. but I do strongly recommend you avoid underscores, it makes the function names harder to read. My personal style is FunctionName, because it's concise, and idk it's less obnoxious to me. – MarcusJ Aug 04 '15 at 08:44
  • 3
    I personally prefer `snake_case` over `camelCase` because in situations where you have an acronym in a function name (say you have a function that parses XML data) I find `parse_xml_data` much more readable than `parseXMLData`... XML and Data seem to morph into one blob of a word when using `camelCase` – tjwrona1992 Sep 04 '18 at 21:47
  • 3
    @tjwrona1992 it's common standards to use camelCase without capitalizing all letters of the abbreviation, thus in your example it would be common to have `parseXmlData` – johnbakers Jun 02 '20 at 12:35
  • Whenever I see capitalized function name, I feel it's shouting. So when I see a whole page of capitalized functions and function calls, well, well, what can I say. I can only quote that "(a) K&R are right and (b) K&R are right". – zrfrank Jul 30 '21 at 04:44

12 Answers12

62

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • 6
    I disagree. You can use PascalCase for your methods, and then use begin/end names for the specific classes that require it. That is exactly the same as if you were subclassing a struct from an third-party that has a different naming convesion as your own. – Dess Nov 18 '16 at 16:50
  • 16
    @Dess: Yeah but the resulting mix does not make it any better. So if you start a new project, it is a recommendation for sanity not to use PascalCase for function names. – Ray Mar 14 '17 at 20:18
  • I agree with @Dess – Lucas Martins Nov 17 '17 at 13:17
  • 4
    Also, since the global function `main` is in `lowerCamelCase`, I would give it an extra vote, at least for global function names. – endavid Apr 17 '19 at 09:53
  • Excellent point. And I would add that in the wide world there are way way way more java functions and c-functions and c++ functions starting from lower case, than c++ and c# functions starting from capital letter. – uuu777 Sep 02 '21 at 13:26
  • 3
    @endavid `main` is no more camelCase than snake_case. – Quirin F. Schroll Jan 27 '22 at 08:48
50

There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.

From said guide:

Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().

Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99
int3
  • 12,861
  • 8
  • 51
  • 80
  • 40
    There is a standard way... The standard naming convention used in all standard library code is my_name, except for MACRO_NAMES, or TemplateParameterTypeNames. This is derived from unix C conventions. Camel case is a convention derived from microsoft c and c++ code. CamelCase is more difficult to read. – catphive Mar 19 '11 at 20:04
  • 12
    Hungarian notation is from Microsoft. TitleCase and camelCase are much older and have been used outside computing as an alternative to snake_case. – Brent Faust Feb 13 '14 at 03:55
  • 6
    _Actually_ there is a "correct way". Or to be more specific, there is one "incorrect way". Namely, if you want to make your classes work with the __range-based `for`-loop__, [you have to define functions called `begin` and `end`](http://stackoverflow.com/q/8164567/3425536). C++ doesn't support `PascalCase` in this. – Emil Laine Aug 08 '15 at 13:37
  • 1
    @catphive I agree it seems microsoft has used camel case in c++. Also Microsoft developer network gives a fairly concrete and clear layout for camel case. That said I see it is often missused by naming functions with first letter lower case, which according to Microsoft is for function parameter variable names. Though while it doesn't matter, I have gotten flack for it on this site and others. Again personally I find Microsoft code to be most visually appealing, if I dare say I find any code to be visually appealing really. It's least ugly. – marshal craft Nov 09 '17 at 22:57
  • 3
    Also again in my opinion, I find Microsoft to have unified and accelerated the use and adoption of computers more so than any other software company. Google has done a lot for open source, def more originally than Microsoft but I dissagree that open source code alone worth much. Microsoft provided much of the intelligent frame work to guide proprietary and open source software. The internet would not be what it is today if it weren't for the agreement to work together. They intelligently unified hardware like no other company has sense been able to. Even they can't seem to do it again. – marshal craft Nov 09 '17 at 23:03
  • @catphive: Please do not quote the standard library as a style guide. It isn't. Programming like in the C++ standard library is not a useful general standard to write C++ code. The standard library code has a lot of historic constraints and influences. – Johannes Overmann Feb 18 '22 at 18:10
35

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.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Donnie
  • 45,732
  • 10
  • 64
  • 86
  • 2
    This is what I'm using, but what about namespaces? Isn't it weird to have `std::vector` but `Project::Connection::TcpHandler`? – rr- Jul 26 '15 at 12:34
  • 1
    Only if you're adding stuff to std. Otherwise, just be internally consistent. – Donnie Jul 27 '15 at 21:12
  • It's recommended to use snake_case for namespaces as it's easier to differentiate them from classes. I've noticed this in several style guides, most notably the ISO CPP Core Guidelines and the Google Style Guide. – Dinanjanan Oct 05 '21 at 17:01
19

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

Steven Keith
  • 1,789
  • 15
  • 23
15

If you look at the standard libraries the pattern generally is my_function, but every person does seem to have their own way :-/

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • 2
    Why is this not way up. Standard libraries literally tell you the STANDARD for code style in most languages. –  Feb 15 '17 at 07:26
  • 8
    https://xkcd.com/927/ and "the great thing about standards is that there are so many of them" – TofuBeer Feb 16 '17 at 05:20
  • 1
    The C++ Core Guidelines say about this: "Prefer `underscore_style` names. The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ Standard Library. This rule is a default to use only if you have a choice. Often, you don't have a choice and must follow an established style for consistency. The need for consistency beats personal taste. This is a recommendation for when you have no constraints or better ideas." See https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl10-prefer-underscore_style-names – Michael Franzl Dec 27 '20 at 16:01
12

Personally, I prefer thisStyle to ThisStyle for functions. This is really for personal taste, probably Java-influenced, but I quite like functions and classes to look different.

If I had to argue for it, though, I'd say that the distinction is slightly more than just aesthetic. It saves a tiny bit of thought when you come across function-style construction of a temporary. Against that, you can argue that it doesn't actually matter whether Foo(1,2,3) is a function call or not - if it is a constructor, then it acts exactly like a function returning a Foo by value anyway.

The convention also avoids the function-with-same-name-as-a-class-is-not-an-error fiasco that C++ inherits because C has a separate tag namespace:

#include <iostream>

struct Bar {
    int a;
    Bar() : a(0) {}
    Bar(int a) : a(a) {}
};

struct Foo {
    Bar b;
};

int Bar() {
    return 23;
}

int main() {
    Foo f;
    f.b = Bar();
    // outputs 23
    std::cout << f.b.a << "\n";
    // This line doesn't compile. The function has hidden the class.
    // Bar b;
}

Bar is, after all, both a noun and a verb, so could reasonably be defined as a class in one place and a function in another. Obviously there are better ways to avoid the clash, such as proper use of namespaces. So as I say, really it's just because I prefer the look of functions with lower-case initials rather than because it's actually necessary to distinguish them from from classes.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
6

Unlike Java, C++ doesn't have a "standard style". Pretty much very company I've ever worked at has its own C++ coding style, and most open source projects have their own styles too. A few coding conventions you might want to look at:

It's interesting to note that C++ coding standards often specify which parts of the language not to use. For example, the Google C++ Style Guide says "We do not use C++ exceptions". Almost everywhere I've worked has prohibited certain parts of C++. (One place I worked basically said, "program in C, but new and delete are okay"!)

Ruurd Adema
  • 920
  • 7
  • 17
Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • 1
    "program in C, but new and delete are okay" - that's opening a big can of worms, just to type `Foo *foo = new Foo;` instead of `Foo *foo = malloc(sizeof(Foo)); assert(foo);` ;-) – Steve Jessop Nov 21 '09 at 19:16
  • Well yeah, that was the point. At that company we pretty much always used new and delete instead of malloc and free. Other that that it was practically just C though: no constructors, methods, templates or exceptions allowed. They were building embedded software and were afraid that they might need to port to a platform that didn't have a C++ compiler (this was almost 15 years ago). – Laurence Gonsalves Nov 21 '09 at 19:36
  • 1
    Sounds mad as a hatstand to me. If they're worried they might need a platform without C++, they could write C, and get the benefit that by compiling it with `-std=c89 -pedantic` they can actually be validating it as C89, which will work in a C compiler, instead of C++, which might not. If they wanted so desperately to type "new" and "delete", use a couple of macros (admittedly you'd need extra parentheses: `delete(new(TYPE));` instead of `delete new TYPE;`. – Steve Jessop Nov 22 '09 at 01:30
  • 1
    I never said it was a good convention. I only mentioned it as an example of how extreme the "forbidden parts of C++" type of coding convention can get. – Laurence Gonsalves Nov 22 '09 at 04:55
4

I think its a matter of preference, although i prefer myFunction(...)

sud03r
  • 19,109
  • 16
  • 77
  • 96
4

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.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
  • "K&R" is an indentation style, not a capitalization style, so this is not answering the question. See https://en.wikipedia.org/wiki/Indentation_style#K&R_style Also, the link is broken. Now located here: https://www.stroustrup.com/bs_faq2.html#Hungarian . However, Stroustrup writes there: "I prefer to use underscores to separate words in an identifier (e.g, element_count) rather than alternatives, such as elementCount and ElementCount." – Michael Franzl Dec 27 '20 at 09:46
3

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

Dani
  • 14,639
  • 11
  • 62
  • 110
3

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.

Daniel Bingham
  • 12,414
  • 18
  • 67
  • 93
2

It all depends on your definition of correct. There are many ways in which you can evaluate your coding style. Readability is an important one (for me). That is why I would use the my_function way of writing function names and variable names.

Peter Stuifzand
  • 5,084
  • 1
  • 23
  • 28