黑马程序员-- C语言变量作用域与代码块

这里通过变量作用域的两种错误用法来介绍一下C语言变量作用域

其次对代码块的使用进行了简单说明:

#include <stdio.h>

 1.变量的作用域(作用范围)

    变量定义的那一行开始,直到变量所在的代码块结束为止。

 2.代码块

    作用:及时回收不再使用的变量,提高程序性能

-----------------------------------------------------------------------------

下面两种做法是错误的,都是在变量作用域之外使用它。

做法一: 

int main(){

    int score;

    score = a + 10;

    int a = 100;

    return 0;

}

运行结果:变量使用注意.c:7:13: error: use of undeclared identifier 'a'

         score = a + 10;

                 ^

1 error generated.

 -----------------------------------------------------------------------------

做法二: 

int test()

{

    int score = 100;

    return 0;

}

int main()

{

    test();

    printf("%d",score);

    return 0;

}

 运行结果:变量使用注意.c:26:17: error: use of undeclared identifier 'score'

 printf("%d",score);

             ^

 1 error generated.

 ----------------------------------------------------------------------------

代码块的使用

int main()

{

    float height = 1.65;

    height = height + 0.1;

    int score = 100;

    //...没有再使用height

    printf("%d",score);

}

上边main函数中,变量height在执行:height = height + 0.1之后再也没用到height,为了提高程序性能,可以如下使用代码块:

int main()

{

    {

        float height = 1.65;

        height = height + 0.1;

    }//代码块执行完后,变量height从程序内存中释放

    int score = 100;

    //...没有再使用height

    printf("%d",score);

}

-----------------------------------------------------------------------------

代码块的例子:

int main()

{

    int a = 20;

    int score = a + 100;

    printf("%d\n",score);//120

    {

        int score = 50;

        {

            score = 10;

            printf("%d\n",score);//10

        }

        a = 10;

    }

    {

        score = a +250;

        int score =30;

        printf("%d\n",score);//30

    }

    printf("%d\n",score);//260

    return 0;

}

代码块内部使用它自己没有定义的变量,这个变量就是该代码块向它外层找最近定义的那个代码块中的变量。

posted @ 2014-05-04 14:36  黑马--刘元明  阅读(267)  评论(0)    收藏  举报