2026-11-09
find_user.c
#include <stdio.h>
#include <string.h>
int find(const char* names[], int n, const char* key) {
for (int i = 0; i < n; i++) {
if (strcmp(names[i], key) == 0) {
return i;
}
}
return -1;
}
int main(void) {
const char* users[] = {"root", "alice", "bob"};
printf("root: %s\n", find(users, 3, "root") ? "yes" : "no");
printf("eve: %s\n", find(users, 3, "eve") ? "yes" : "no");
}
利用者の名簿 users に名前が載っているかを yes か no で表示するつもりのプログラムです。find は名前を見つけた添字を返し、見つからなければ -1 を返します。名簿にある root と、名簿にない eve を調べると、本来は root: yes と eve: no の2行が出るはずが、いまは root: no と eve: yes の2行が出ます。
Answer
Wrong
printf("root: %s\n", find(users, 3, "root") ? "yes" : "no");
printf("eve: %s\n", find(users, 3, "eve") ? "yes" : "no");
条件演算子 ?: の条件は、0なら偽、0以外ならすべて真として扱われます。find の戻り値は見つけた添字で、root は名簿の先頭にあるので0が返ります。添字としては正しい0が条件では偽になり、no が選ばれます。eve は見つからないので -1 が返り、-1 は0ではないので真になって yes が選ばれます。alice や bob を調べれば1や2が返って yes と正しく出るので、名簿の先頭の名前と名簿にない名前だけで結果が逆になります。
Right
printf("root: %s\n", find(users, 3, "root") >= 0 ? "yes" : "no");
printf("eve: %s\n", find(users, 3, "eve") >= 0 ? "yes" : "no");
find の戻り値は、0以上なら添字、-1なら見つからなかったことを表します。見つかったかどうかは真偽ではなく、この取り決めに合わせて >= 0 で比べます。root の0も >= 0 を満たして yes になり、eve の -1 は満たさないので no になります。find の側を直さないのは、戻り値の添字をそのまま配列に使う呼び出し方を残すためです。