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

C++での値の渡し方

Last updated at Posted at 2025-08-18

初めに

初めて記事を書かせていただきます藤田拓未と申します。
大学3年です。主にポートフォリオの作成の際に勉強したことを自分へのメモとして書いていきます。
##C++の参照渡しについて

通常の戻り値で返す方法

#include <iostream>
using namespace std;

int pass_value(int num) {
    num += 1;
    return num;
}
int main() {
    int value0 = 10;
    cout << "v0の値は" << value0 << endl;
    value0 = pass_value0(value0);
    cout << "v0の値は" << value0 << endl;
    return 0;
}

参照渡し

#include <iostream>
using namespace std;

void pass_by_value(int &v0,int &v1) {
    v0 = 20;
    v1 = 1;
}
int main() {
    int value0 = 10;
    int value1 = 12;
    
    cout << "v0の値は:" << value0 << ", v1の値は:" << value1 << endl;
    pass_by_value(value0, value1);
    cout << "v0の値は:" << value0 << ", v1の値は:" << value1 << endl;
    
    return 0;
}

ポインタを使った渡し方

#include <iostream>
using namespace std;

void pass_pointer(int* v0, int* v1) {
    if (v0 != nullptr && v1 != nullptr) {
        *v0 = 100;
        *v1 = 200;
    }
}

int main() {
    int value0 = 10;
    int value1 = 12;
    
    cout << "v0の値は:" << value0 << ", v1の値は:" << value1 << endl;
    pass_pointer(&value0, &value1);
    cout << "v0の値は:" << value0 << ". v1の値は:" << value1 << endl;

    return 0;
}

参照渡しや、ポインタを使って値を渡すことで、複数の値を渡すことができます。また、mainの値を書き換えることができます。

コメントで指摘してくださった皆様ありがとうございました。
修正いたしました。

0
0
5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?