Function Naming Rules in C++
In C++, function names follow specific rules and conventions to ensure clarity, consistency, and compatibility. Proper naming is essential for code readability and maintainability.
In this tutorial, we shall go through the rules for naming functions in C++, best practices for naming functions, examples for valid function names and invalid function names.
Rules for Naming Functions
- Alphanumeric Characters and Underscores: Function names can consist of letters (
A-Z
,a-z
), digits (0-9
), and underscores (_
). - Must Begin with a Letter or Underscore: The first character of a function name must be a letter or an underscore. It cannot start with a digit.
- Case Sensitivity: Function names in C++ are case-sensitive. For example,
addNumbers
andAddNumbers
are treated as two different functions. - No Reserved Keywords: Function names cannot be the same as C++ reserved keywords (e.g.,
int
,return
,if
). - Length Restrictions: There is no explicit limit to the length of a function name, but shorter, meaningful names are recommended for readability.
Best Practices for Function Naming
- Use Descriptive Names: Choose names that clearly describe the function’s purpose. For example, use
calculateSum
instead ofcs
. - CamelCase or snake_case: Follow a consistent naming convention:
- CamelCase: Capitalize the first letter of each word except the first (e.g.,
calculateSum
). - snake_case: Use underscores to separate words (e.g.,
calculate_sum
).
- CamelCase: Capitalize the first letter of each word except the first (e.g.,
- Use Action Verbs: Begin function names with action verbs to indicate what the function does, such as
getData
,computeAverage
, orprintResults
. - Avoid Abbreviations: Avoid overly abbreviated names unless they are widely recognized (e.g., you may use
calcSum
instead ofcs
). - Consistency Across Projects: Follow a consistent naming style across the entire codebase for uniformity.
Examples of Valid Function Names
Function Name | Description |
---|---|
calculateSum | Valid name in CamelCase that describes its purpose. |
find_max_value | Valid name in snake_case with underscores separating words. |
_initializeData | Starts with an underscore, which is allowed. |
compute_average_2023 | Includes numbers, which are allowed as long as they are not the first character. |
Examples of Invalid Function Names
Function Name | Reason |
---|---|
123Calculate | Starts with a digit, which is not allowed. |
return | Uses a reserved keyword, which is not allowed. |
calculate-sum | Contains a hyphen, which is not allowed. |
sum@value | Contains an invalid character (@ ), which is not allowed. |