c语言如何跳转到特定函数

avatar
作者
筋斗云
阅读量:4

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

以上两种方法都可以根据条件选择特定的函数进行跳转。使用函数指针可以更灵活地动态选择函数,而条件语句则更直观简洁。具体选择哪种方法取决于实际需求和个人偏好。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!