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 and AddNumbers 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

  1. Use Descriptive Names: Choose names that clearly describe the function’s purpose. For example, use calculateSum instead of cs.
  2. 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).
  3. Use Action Verbs: Begin function names with action verbs to indicate what the function does, such as getData, computeAverage, or printResults.
  4. Avoid Abbreviations: Avoid overly abbreviated names unless they are widely recognized (e.g., you may use calcSum instead of cs).
  5. Consistency Across Projects: Follow a consistent naming style across the entire codebase for uniformity.

Examples of Valid Function Names

Function NameDescription
calculateSumValid name in CamelCase that describes its purpose.
find_max_valueValid name in snake_case with underscores separating words.
_initializeDataStarts with an underscore, which is allowed.
compute_average_2023Includes numbers, which are allowed as long as they are not the first character.

Examples of Invalid Function Names

Function NameReason
123CalculateStarts with a digit, which is not allowed.
returnUses a reserved keyword, which is not allowed.
calculate-sumContains a hyphen, which is not allowed.
sum@valueContains an invalid character (@), which is not allowed.