Function/Variable Scope   «Prev  Next»
Lesson 1

Functions and scope in C++

  1. Syntax, Use, and Scope of C++ Functions and Variables
    • Functions in C++:
      • Syntax:
        return_type function_name(parameter_list) {
            // Function body
        }
                    
        • return_type: The data type of the value returned by the function (e.g., int, float, void).
        • function_name: The name of the function.
        • parameter_list: The list of parameters with their data types, separated by commas.
      • Use:
        • Functions in C++ are used to modularize code, making it more organized, easier to read, and reusable.
        • Functions can perform operations and return results to the caller. C++ allows function overloading, where multiple functions can share the same name but differ in the number or type of parameters.
      • Scope of Variables:
        • Local Scope: Variables defined inside a function or block are accessible only within that block and are destroyed once the block exits.
          void example() {
              int localVar = 10; // Local scope
          }
                          
        • Global Scope: Variables defined outside of all functions are accessible throughout the file. They have program-wide scope and retain their values throughout the execution of the program.
          int globalVar = 20; // Global scope
                          
        • Static Variables: Variables declared with the static keyword inside a function retain their value between function calls.
          void example() {
              static int count = 0; // Static variable
              count++;
          }
                          
  2. Inlining in C++
    • Concept:
      • Inlining in C++ is a mechanism where the compiler replaces a function call with the actual code of the function. This can reduce the overhead of function calls, especially in small, frequently called functions.
    • Syntax:
      inline return_type function_name(parameter_list) {
          // Function body
      }
              
      • You use the inline keyword before the function definition. Note that placing the function definition inside the class definition also implies that the function may be inlined.
    • Use:
      • Small Functions: Inline functions are best suited for small, frequently called functions, as inlining large functions may increase the size of the binary and reduce performance.
      • Performance: By avoiding the overhead of a function call (like pushing/popping the call stack), inlining can lead to performance gains.
    • Scope and Compiler Behavior:
      • The inline keyword is only a request to the compiler. The compiler may decide not to inline a function if inlining would result in excessive code bloat or complexity.
      • Inline functions must be defined in a header file if they are used in multiple translation units (i.e., across multiple source files).

Example of an Inline Function:
inline int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(5, 10); // The compiler may replace this with `int result = 5 + 10;`
    return 0;
}

Summary:
  • Functions in C++ are similar to those in C, but C++ offers enhancements like overloading and inlining for better performance and flexibility.
  • The inline keyword suggests to the compiler to replace function calls with the function’s body, but the compiler can decide whether to honor this request based on optimization strategies.


Big C++
This module explores the syntax, use, and scope of C++ functions and variables. Functions are very similar in C and C++, but C++ offers some useful improvements, including overloading and inlining. C++ also offers storage classes similar to those of C, which are essential in writing multifile programs.
  • Module Objectives You will learn:
    1. How C++ uses function prototypes
    2. How using default function arguments can save you time
    3. What it means to overload a function
    4. How to use the keyword inline to speed up programs
    5. The difference between file scope and local scope
    6. How the extern and static storage classes are useful in multifile programs
    7. The rules of linkage for multifile programs
    8. What namespaces are and why they are useful

    At the end of the module, you will be given the opportunity to take a quiz covering these topics.

Purpose of C++ Functions

The main way of getting something done in a C++ program is to call a function to do it. Defining a function is the way you specify how an operation is to be done and a function cannot be called unless it has been previously declared.
A function declaration gives
  1. the name of the function,
  2. the type of the value returned (if any), and
  3. the number and types of the arguments that must be supplied in a call.

Elem. next_elem();     // no argument; return a pointer to Elem (an Elem*)
void exit(int);     // int argument; return nothing
double sqrt(double);     // double argument; return a double

In a function declaration, the return type comes before the name of the function and the argument types after the name enclosed in parentheses.The semantics of argument passing are identical to the semantics of copy initialization. That is, argument types are checked and implicit argument type conversion takes place when necessary.

SEMrush Software