溫馨提示×

c語言如何跳轉到特定函數

小億
260
2023-10-11 21:22:31
欄目: 編程語言

在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. 使用條件語句:

在條件語句中使用函數調用來選擇執行特定的函數。

#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;
}

以上兩種方法都可以根據條件選擇特定的函數進行跳轉。使用函數指針可以更靈活地動態選擇函數,而條件語句則更直觀簡潔。具體選擇哪種方法取決于實際需求和個人偏好。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女