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

bookConstant Function Arguments

メニューを表示するにはスワイプしてください

Note
Definition

Constant arguments in a function indicate that the values passed to the function as parameters cannot be modified inside the function.

Pass const Arguments by Value

When a parameter is passed by value and declared as const, a copy of the value is made, and the function cannot modify that copy.

To declare the constant argument, you have to use const keyword before the type specifier of the argument inside the signature of the function. The const keyword acts as a clarifier, showing that the function does not change the passed value.

main.cpp

main.cpp

copy
1234567891011
#include <iostream> double square(const double number) { return number * number; } int main() { std::cout << square(25); }

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

Pass const arguments by pointer/reference

Using const with pointers or references protects the original data from modification. Passing by pointer or reference saves memory, but const ensures the original value remains unchanged inside the function.

main.cpp

main.cpp

copy
12345678910111213141516171819
#include <iostream> // Function definition double area(const double* radiusPtr, const double& pi) { // Check if the pointer and reference are not null if (*radiusPtr > 0) return pi * (*radiusPtr) * (*radiusPtr); return 0; // Invalid radius, return 0 } int main() { double radius = 5.0; double pi = 3.14159; double result = area(&radius, pi); std::cout << "Area of the circle with radius " << radius << " is: " << result << std::endl; }
question mark

Which function signature shows a constant reference to an integer?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  8

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  8
some-alt