値渡し/ポインタ渡し/参照渡しによる引数の受け渡し
メニューを表示するにはスワイプしてください
値渡し
関数内で作成された変数は、その関数内でのみアクセス可能。このルールは引数を渡す場合にも適用される。関数シグネチャ内のパラメータはローカルスコープを持ち、値渡しで渡される。つまり、値が関数内にコピーされ、別の変数として保存される(元の本を持ち出すのではなく、図書館の本を借りるイメージ)。
main.cpp
1234567891011121314151617181920#include <iostream> // Function that takes an argument by value void modify(int num) { // Modify the parameter (local copy of the argument) num = num * 2; } int main() { int number = 5; std::cout << "Before function call: " << number << std::endl; // Call the function and pass 'number' by value modify(number); // Varibale in the main function remains unchanged std::cout << "After function call: " << number << std::endl; }
ポインタ渡し
引数を値渡しするのは、常に効率的とは限らない。値をコピーすると余分なメモリを使用し、関数が元の変数を直接変更する必要がある場合もある。このような場合は、変数をポインタ渡し(値ではなくメモリアドレスを渡す)する方が適している。これは、関数パラメータでポインタ演算子(*)を使って行う。
main.cpp
1234567891011121314151617181920212223#include <iostream> // Function that takes an argument using pointer void modify(int* p_num) { // Modify the value at the memory address pointed by `p_num` // '*' is used to extract the value from the address (pointer) *p_num = (*p_num) * 2; std::cout << "Inside function: " << *p_num << std::endl; } int main() { int number = 5; std::cout << "Before function call: " << number << std::endl; // Call the function and pass the address of 'number' using a pointer // '&' is used to get an address of the variable modify(&number); // 'number' in the main function is modified through the pointer std::cout << "After function call: " << number << std::endl; }
参照渡し
参照渡しは、関数に変数のメモリアドレスへの直接アクセスを与える方法であり、デリファレンス演算子(*)を使わずに元の値を変更可能。
参照渡しは、関数のパラメータで**&演算子**を使用。ポインタ渡しと似ているが、主に2つの違いがある:
- 関数内で変数にアクセスする際に**
*を使う必要がない**。 - 関数を呼び出す際に**
&を使う必要がない**(宣言時のみ必要)。
main.cpp
1234567891011121314151617181920#include <iostream> // Function that takes an argument by reference void modify(int& num) { // Modify the parameter directly (no need for dereferencing) num = num * 2; } int main() { int number = 5; std::cout << "Before function call: " << number << std::endl; // Call the function and pass `number` by reference modify(number); // `number` in the main function is modified directly through the reference std::cout << "After function call: " << number << std::endl; }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 2
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 2