1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑫~関数の作成~

Last updated at Posted at 2022-07-10

関数の作成

自分で関数を作成することを関数を定義するという
関数はデータを投入すると処理を行い、新しい結果を返します

関数を作成するメリット

  • プログラムの可読性が向上する
  • 再利用することができ、何度も同じコードを書く必要がなくなる

関数の構文

返り値の型 関数名(引数の型 引数の名前, ...) {
  // 処理
  return 返す値;
}

小さい値を返す関数

#include <iostream>

using namespace std;

int my_min(int x, int y) {
 
  if (x < y) {
    return x;
  }
  else {
    return y;
  }
 
}
 
int main() {
  int answer = my_min(10, 5);
  cout << answer << endl;
}
5

返り値がない関数

返り値の型voidにすることで、返り値のない関数を作成できる

#include <iostream>

using namespace std;

void hello() {
  cout << "Hello World!" << endl;
}
 
int main() {
  hello();
  return 0;
}
Hello World!

呼び出し元よりも上に関数を定義する

関数の呼び出し元よりも下に関数を定義するとエラーが発生する

#include <iostream>

using namespace std;

int main() {
  hello();
  return 0;
}

void hello() {
  cout << "Hello World!" << endl;
}
ビルドを開始しています...
C:\MinGW\bin\g++.exe -fdiagnostics-color=always -g C:\Git\C++\test.cpp -o C:\Git\C++\test.exe
C:\Git\C++\test.cpp: In function 'int main()':
C:\Git\C++\test.cpp:6:3: error: 'hello' was not declared in this scope
    6 |   hello();
      |   ^~~~~

ビルドが完了しましたが、エラーが発生しました。

プロトタイプ宣言

関数名引数と返り値だけを先に宣言する

#include <iostream>

using namespace std;

// プロトタイプ宣言
void hello();

int main() {
  hello();
  return 0;
}

void hello() {
  cout << "Hello World!" << endl;
}
Hello World!

次の記事

【C++】基礎を学ぶ⑬~配列~

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?