Menu
CoddyTech

関数の引数は値

Coddyの「C++開発者のためのC」コースのレッスン 17/48。

C++は値渡し引数と参照渡し引数の両方をサポートしています。Cでは値渡し引数のみが使用されます。ポインターをコピーすると、そのポインターが指すオブジェクトにアクセスできますが、C++の参照束縛の意味論が生じるわけではありません。

Cの引数はすべて値渡しされます。ローカルの仮引数を更新しても、呼び出し元の変数は置き換わりません。

C++の例

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
void change(int x){x=9;(void)x;}
int main(){
int x=2;change(x);std::cout<<x<<"\n";
}

C++の出力:

2

Cの例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static void change(int n){n=9;(void)n;}
int main(void) {
int x=2;change(x);printf("%d\n",x);
return 0;
}

Cの出力:

2
challenge icon

チャレンジ

簡単

入力は整数 n です。呼び出し元のコピーを変更せずに、n を2倍にして返してください。ドライバーはoriginal:doubledを出力します。

ロックされていないソースファイルとヘッダーファイルを編集してください。表示されているロック済みのmain.cから直接呼び出される、宣言済みの公開APIとの互換性を保ってください。別のmainを追加しないでください。タスクで範囲が明示的に確認される場合を除き、数値のテストデータはすべてオーバーフローしない小さな値です。指定された出力だけを出力してください。入力解析と、例に示されている場合の出力はドライバーが行います。

自分で試してみよう

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n;if(scanf("%d",&n)!=1)return 1;int result=doubled(n);printf("%d:%d\n",n,result);return 0;}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのCのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ