Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 関数におけるreturn文 | 関数の導入
C++入門

book関数におけるreturn文

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

return文は、関数の実行を終了し、あらかじめ定義された型の値を返す。

function.h

function.h

copy
12345
int func() // int - predefined { int variable = 10; return variable; // variable = 10 }

型が正しく指定されていない場合、関数は予測できない動作をする。

main.cpp

main.cpp

copy
12345678910111213
#include <iostream> unsigned short func() { return -10; } // The unsigned short data type has no negative values. int main() { std::cout << func() << std::endl; }

つまり、関数を作成する前に、その関数が返すデータ型を指定する必要がある。また、C++ には特別なvoid関数が存在する。このデータ型の関数は何も返さないことが許可されている:

first_example.cpp

first_example.cpp

second_example.cpp

second_example.cpp

copy
123456789101112
#include <iostream> void voidFunction() { std::cout << "It's void function!" << std::endl; // Function without return } int main() { voidFunction(); }

関数内には複数のreturn文を記述でき、それぞれは特定の条件下でのみ実行される。

main.cpp

main.cpp

copy
1234567891011121314151617
#include <iostream> int func() { int a = 50; int b = 6; if (a > b) // If `a > b`, func will `return a` return a; else // Otherwise func will `return b` return b; } int main() { std::cout << func() << std::endl; // Func calling }

return文が2つある場合、2つ目のreturn文は無視される。

main.cpp

main.cpp

copy
123456789101112131415
#include <iostream> int func() { int a = 50; // Declare variable a int b = 6; // Declare variable b return a; // Function stops here, b is never returned return b; // Unreachable } int main() { std::cout << func() << std::endl; // Call func and print result }
question mark

関数内で return 文が実行されると何が起こりますか?

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

すべて明確でしたか?

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

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

セクション 5.  3

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 5.  3
some-alt