C 函数范围

2018-07-04 11:32 更新

学习C - C函数范围

静态变量

静态变量可以保留从一个函数调用到的信息下一个。

您可以使用此声明声明一个静态变量 count :

static int count = 0;

单词static是一个关键字。

单词static是一个关键字。...

被声明为静态的变量的初始化只发生一次,就在开头程序。

虽然静态变量仅在包含其声明的函数内可见,它本质上是一个全局变量。

以下代码显示了静态变量和自动变量之间的差异。


    #include <stdio.h> 

    // Function prototypes 
    void test1(void); 
    void test2(void); 
      
    int main(void) { 
      for(int i = 0 ; i < 5 ; ++i) { 
        test1(); 
        test2(); 
      } 
      return 0; 
    } 
    // Function test1 with an automatic variable 
    void test1(void) 
    { 
      int count = 0; 
      printf("test1   count = %d\n", ++count ); 
    } 

    // Function test2 with a static variable 
    void test2(void) 
    { 
      static int count = 0; 
      printf("test2   count = %d\n", ++count ); 
    } 

上面的代码生成以下结果。



在函数之间共享变量

为了在函数之间共享变量,在程序文件的开头声明一个变量所以他们“超出了功能的范围。

这些被称为全局变量,因为它们“可以随时随地访问。


    #include <stdio.h> 
      //w w w. jav  a  2  s  .  c  o  m
    int count = 0;                         // Declare a global variable 
      
    // Function prototypes 
    void test1(void); 
    void test2(void); 
      
    int main(void) { 
      int count = 0;                       // This hides the global count 
      
      for( ; count < 5 ; ++count) { 
        test1(); 
        test2(); 
      } 
      return 0; 
    } 
      
    void test1(void) { 
      printf("test1   count = %d\n", ++count); 
    } 
    void test2(void) { 
      printf("test2   count = %d\n", ++count); 
    } 

上面的代码生成以下结果。



函数递归

一个函数可以调用自身。这称为递归。

调用自身的函数也必须包含停止过程的方式。

以下代码显示如何计算整数的阶乘。

任何整数的阶乘是所有从1到的整数的乘积整数本身。


    #include <stdio.h> 
      /*  w w w. j a  v  a2  s.  c om*/
    unsigned long long factorial(unsigned long long); 
      
    int main(void) { 
      unsigned long long number = 10LL; 
      printf("The factorial of %llu is %llu\n", number, factorial(number)); 
      return 0; 
    } 
    // A recursive factorial function 
    unsigned long long factorial(unsigned long long n) { 
      if(n < 2LL) 
        return n; 
         
      return n*factorial(n - 1LL); 
    } 

上面的代码生成以下结果。

abort()函数

调用abort()函数会导致程序异常终止。

它不需要参数。

当你想结束一个程序时,这样调用:

abort();                          // Abnormal program end

exit()和atexit()函数

exit()函数导致程序的正常终止。

该函数需要一个类型的参数int表示终止时的程序状态。

参数可以为0或EXIT_SUCCESS以指示a成功终止,并将其返回到主机环境。

例如:

exit(EXIT_SUCCESS);               // Normal program end

如果参数是EXIT_FAILURE,则将向主机环境返回故障终止的指示。

您可以通过调用atexit()注册您自己的函数,由exit()调用。

您调用atexit()函数来标识要执行的函数当应用程序终止时。

这里的你怎么可能这样做:

void CleanUp(void);// Prototype of function

if(atexit(CleanUp)) 
  printf("Registration of function failed!\n"); 
 

_Exit()函数

_Exit()函数与exit()基本上执行相同的工作。

_Exit()不会调用任何注册的函数。

你调用_Exit()像这样:

_Exit(1);                         // Exit with status code 1 
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号