7.2 引数
7.2.1 引数の実装
関数に値を渡すときは、以下のように実装する。
cpp
#include <iostream>
using namespace std;
int triple(int x) {
cout << x*3 << endl;
return 0;
}
int main() {
triple(4);
triple(3);
}Output
12
9この関数に渡す値のことを引数と呼ぶ。 引数の型は()の内側で定義される((int x)の部分)。
例えばstring型の引数を設定したいなら以下のように実装する。
cpp
#include <iostream>
using namespace std;
int hello(string s) {
cout << "Hello, " << s << endl;
return 0;
}
int main() {
hello("traP");
hello("Takeno_hito");
}Output
Hello, traP
Hello, Takeno_hito引数は複数個設定することもできる。
cpp
#include <iostream>
using namespace std;
int add(int x, int y) {
cout << x + y << endl;
return 0;
}
int main() {
int a = 5;
int b = 10;
add(4, 7);
add(a, b);
}Output
11
15引数は、関数内でしか使うことができない(関数を呼び出した側の変数は変わらない)。
cpp
#include <iostream>
using namespace std;
int triple(int x) {
x = x*3;
return 0;
}
int main() {
int x = 4;
triple(x);
cout << x << endl;
}Output
4これについての詳細は7.4で扱う。