Conteúdo do Curso
C++ Functions
C++ Functions
Constant 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:
example
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.
main
#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; }
Obrigado pelo seu feedback!