`C言語で特定の関数へジャンプする方法`

C言語において、特定の関数にジャンプするには、関数ポインタか条件文を利用できる。

  1. ファンクションポインタを使う

はじめに、関数ポインタ型を定義し、その型のポインタ変数を定義し、関数のアドレスをそのポインタ変数に代入し、最後にそのポインタ変数から関数を呼び出す。

#include <stdio.h>
void foo() {
printf("This is foo function\n");
}
void bar() {
printf("This is bar function\n");
}
int main() {
void (*func)() = NULL; // 定义函数指针变量
int choice;
printf("1. Call foo()\n");
printf("2. Call bar()\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1) {
func = foo; // 将函数的地址赋值给函数指针变量
} else if (choice == 2) {
func = bar;
}
if (func != NULL) {
(*func)(); // 通过函数指针变量调用对应的函数
} else {
printf("Invalid choice\n");
}
return 0;
}
  1. if 文を使用:

条件文で関数呼び出しを使用して特定の関数を呼び出す。

#include <stdio.h>
void foo() {
printf("This is foo function\n");
}
void bar() {
printf("This is bar function\n");
}
int main() {
int choice;
printf("1. Call foo()\n");
printf("2. Call bar()\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1) {
foo(); // 调用foo函数
} else if (choice == 2) {
bar(); // 调用bar函数
} else {
printf("Invalid choice\n");
}
return 0;
}

どちらの方法も条件によって特定の関数を指定してジャンプできます。関数ポインタを利用すると、より柔軟に動的に関数を選択できますが、条件分岐ではより直感的にシンプルに表現できます。どちらの方法を採用するかは、実際のニーズや個人の好みによって異なります。

bannerAds