Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Constant Function Arguments | Function Arguments Specification
C++ Functions
course content

Course Content

C++ Functions

C++ Functions

1. Introduction
2. Function Arguments Specification
3. Function Return Values Specification
4. Some Advanced Topics

bookConstant Function Arguments

In C++, constant arguments in a function indicate that the values passed to the function as parameters cannot be modified inside the function. To declare the constant argument, we have to use const keyword before the type specifier of the argument inside the signature of the function:

Now let's consider the difference between using const with pass by value and pass by pointer/reference arguments.

Pass const arguments by value

When a parameter is passed by value and declared as const, it means a copy of the value is made, and the function cannot modify that copy.
In this case the const qualifier serves as documentation, indicating to other developers that the function does not modify the parameter:

h

example

copy
1234
double calculateSquare(const double number) { return number * number; }

The const qualifier ensures that the number parameter cannot be modified within the calculateSquare() function, and we can be sure about the integrity of the copied data.

Pass const arguments by pointer/reference

Using constants with pointers or references ensures the preservation of the original data, unlike when arguments are passed by value. While memory optimization often necessitates passing parameters through pointers or references, it becomes crucial to maintain the integrity of the original data within the function.

cpp

main

copy
12345678910111213141516171819
#include <iostream> // Function definition double calculateArea(const double* radiusPtr, const double& pi) { // Check if the pointer and reference are not null if (*radiusPtr > 0) return pi * (*radiusPtr) * (*radiusPtr); else return 0; // Invalid radius, return 0 } int main() { double radius = 5.0; double pi = 3.14159; double area = calculateArea(&radius, pi); std::cout << "Area of the circle with radius " << radius << " is: " << area << std::endl; }
Which of the following function signatures indicates a constant reference to an integer parameter?

Which of the following function signatures indicates a constant reference to an integer parameter?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
some-alt