c语言让函数只执行一次

在C语言中,可以通过静态变量或者全局变量的方式来让函数只执行一次。

静态变量:在函数内部声明一个静态变量,判断其是否为首次执行,如果是,则执行函数体内的代码;如果不是则直接返回。

全局变量:在函数外部声明一个全局变量,在函数内部判断其是否为首次执行,如果是,则执行函数体内的代码;如果不是则直接返回。

下面是一个示例代码:

#include <stdio.h>
int flag = 0;
void only_once()
    if (flag == 0)
        printf("This function is executed for the first time.\n");
        flag = 1;
int main()
    only_once();
    only_once();
    only_once();
    return 0;

运行结果:

This function is executed for the first time.
        没有名气的小透明
        JavaScript