LoginSignup
0
0

More than 1 year has passed since last update.

【C】初めてのC言語(5. 関数)

Last updated at Posted at 2022-05-14

はじめに

学習環境

  • 今回はpaiza.ioのC言語のエディタを使いました。

関数とは

  • プログラムを戻り値つきのサブルーチンに分離したもの。
    • 戻り値がない場合はvoidを指定します。
    • 関数の戻り値の型指定がない場合は、(暗黙的に)int型とみなされます。

サンプルコード

  • 「関数の戻り値の型指定がない場合は、(暗黙的に)int型とみなされる」という仕様は、1999年の仕様改定で削除されており、現行の仕様では戻り値の省略はできないそうです。
    • @SaitoAtsushi さん、ご指摘ありがとうございました。

引数のない関数の例

  • Main関数から、引数なし・戻り値がint型の関数testを呼び出しています。
    • 関数宣言において()のように引数を省略すると、引数が未知と判断されるそうなので、明示的にvoidを入れています。
Main.c
#include <stdio.h>
int test(void) {
    printf("This is test.");
    return 0;
}

int main(void){
    test();
    return 0;
}
実行結果
This is test.

引数のある関数の例

  • 関数calcAreaは、引数が四角形の幅(int型)と高さ(int型)、戻り値が四角形の面積(int型)となっています。
  • ここまでの関数はJavaやC#のメソッドとほぼ同じなので、特に引っかかる点はありませんでした。
Main.c
#include <stdio.h>
int calcArea(int width, int height) {
    return width * height;
}

int main(void){
    int width = 3;
    int height = 4;
    int area = calcArea(width, height);
    printf("幅%d、高さ%dの四角形の面積は%dです。", width, height, area);
    return 0;
}
実行結果
幅3、高さ4の四角形の面積は12です。

引数がポインタの関数の例

  • こちらのページにはポインタのメリットとして以下の2点が挙げられていました。
    • ポインタを引数にすると別関数のローカル変数にアクセスできて便利。
    • 「ポインタ」を利用するケースで最も多いのが、関数からの出力情報を増やしたい時。
  • そこで上記の関数calcAreaを修正して、引数をポインタにしました。
    • 引数:構造体Rectangleのポインタ
    • 戻り値:引数RectAngleのポインタの中身が正常であれば0、異常であれば-1を返す
  • ポインタを引数にすると、構造体のような大きなデータを使って入力値や結果をやり取りするのが便利になります。
  • @fujitanozomu さんのご指摘に沿って、関数calcAreaのコードでアロー演算子を使って修正したところ、かなりスッキリしました。
Main.c
#include <stdio.h>
typedef struct rectangle {   /* rectangle(長方形)はタグ名 */
    int width;               /* 幅 */
    int height;              /* 高さ */
    int area;                /* 面積 */
} Rectangle;

int calcArea(Rectangle* r) {
    if (r->width > 0 && r->height > 0) {
        r->area = r->width * r->height;
        return 0;
    } else {
        return -1;
    }
}

int main(void){
    Rectangle rect;
    rect.width = 3;
    rect.height = 4;
    int errCode = calcArea(&rect);
 
    if (errCode == 0) {
        printf("幅%d、高さ%dの四角形の面積は%dです。", rect.width, rect.height, rect.area);
    } else {
        printf("入力値が異常です。幅:%d、高さ:%d", rect.width, rect.height);
    }
    return 0;
}
実行結果
幅3、高さ4の四角形の面積は12です。

参考URL

0
0
4

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
0
0