ポインターによる複数の結果
Coddyの「C++開発者のためのC」コースのレッスン 19/48。
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 split(int total,int& minutes,int& seconds){minutes=total/60;seconds=total%60;}
int main(){
int minutes=0,seconds=0;split(125,minutes,seconds);std::cout<<minutes<<":"<<seconds<<"\n";
}
C++の出力:
2:5Cの例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static void bounds(int a,int b,int *low,int *high){*low=a<b?a:b;*high=a>b?a:b;}
int main(void) {
int low=0,high=0;bounds(7,2,&low,&high);printf("%d %d\n",low,high);
return 0;
}
Cの出力:
2 7チャレンジ
簡単入力は2つの整数です。bounds(a,b,low,high)を実装し、異なる有効な出力ポインターに小さい方と大きい方の値を書き込みます。ドライバーはlow:highを出力します。
ロックされていないソースファイルとヘッダーファイルを編集してください。表示されているロック済みの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 a,b,low=0,high=0;if(scanf("%d%d",&a,&b)!=2)return 1;bounds(a,b,&low,&high);printf("%d:%d\n",low,high);return 0;}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのCのすべてのレッスン
自分で練習してみよう: Cオンラインコンパイラ