C复习笔记(4)-6.20

来源:互联网 发布:大数据分析有什么用 编辑:程序博客网 时间:2024/05/16 00:51

6.20

(1)

#include <stdio.h>

 

/* count digits, white space,others */

int main()

{

    int c,i,nwhite,nother;

    int ndigit[10];

   

    nwhite = nother = 0;

    for(i = 0; i < 10; i++)

    ndigit[i]=0;

 

    while ((c=getchar()) != EOF) {

    if ((c == ' ') || (c == '/t') || (c == '/n'))

        ++nwhite;

    else if ((c >= '0') && (c <= '9'))

        ++ndigit[c - '0'];

    else

        ++nother;

    }

    printf("%d,%d,",nwhite,nother);

    for(i = 0; i < 10; i++)

     printf("%d,",ndigit[i]);

   

    return 0;

}

Notice: here is a smart expression!

if ((c >= '0') && (c <= '9'))

        ++ndigit[c - '0'];

(2)

In C, all function arguments are passed “by value”. The called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy.

 

When necessary, it is possible to arrange for a function to modify a variable in a calling routine, the called function must declare the parameter to be a pointer and access the variable indirectly through it.

 

The story is different for arrays.

 

Automatic variables:

Come and go with function invocation (include main ()), they do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage.

External variables:

Remain in existence permanently; retain their values even after the functions that set them have returned. It must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.   

“Definition”: refers to the place where the variable is created or assigned storage.

“Declaration”: refers to places where the nature of the variable is stated but no storage is allocated.

 

ok!

原创粉丝点击