C 带静态int的函数

C 带静态int的函数,c,static,C,Static,我有一个C代码: void increase(int x) { static int i=0; x = i + x; i++; printf("x=%d, i=%d\n", x, i); } int main(void) { int i; for (i=0; i<4; i++) increase(i); printf("i=%d\n", i); return 0; } 我不明白如何得到这些结果。当我试图自己运

我有一个C代码:

void increase(int x)
{
    static int i=0;
    x = i + x;
    i++;
    printf("x=%d, i=%d\n", x, i);
}
int main(void)
{
    int i;
    for (i=0; i<4; i++)
        increase(i);
    printf("i=%d\n", i);
    return 0;
}
我不明白如何得到这些结果。当我试图自己运行代码时,我被
静态int
以及函数弄糊涂了;因为函数是以
i
作为参数调用的

由于函数初始化为增加(int x),因此函数执行期间是否将
int i
视为
int x


另外,由于for循环中的第三个表达式是
i++
,并且函数中有一个
i++
,每个i值不应该以2的增量增加吗?谢谢

因为i被声明为静态的,所以它的值在每次函数调用时递增(递增(i))。 这两个i++语句在完全不同的范围内,彼此之间没有任何关系。您不妨将它们视为两个独立的变量。 在主函数中,最初i=0。i的这个值以增量(x)的形式传递给x。由于静态int i=0,x现在为0,i为0。x=x+i等于x=0。然后i++使i=1。这在输出的第一行中演示。同样,在主循环中,i现在是1。这在递增(x)中传递给x。x现在是1。increase()中的i也是1,但这只是因为它被称为静态的,而不是因为main中的i是1。x=x+i等于x=2。i++使i=2。等等

void increase(int x)
{
    static int i=0;
    x = i + x;
    i++;
    printf("x=%d, i=%d\n", x, i);
}
这里i增加1,如输出所示

int main(void)
{
    int i;
    for (i=0; i<4; i++)
        increase(i);
    printf("i=%d\n", i);
    return 0;
}
int main(无效)
{
int i;
对于(i=0;i 0,1,2,3
然后每次给予时增加i->0,1,2,3:

0,2,4,6.

您需要跟踪哪个
i
在哪个函数中可见

void increase(int x)
{static int i=0; /* the only i seen inside this question */
    x = i + x; /* using this functions i, reading it */
    i++;       /* using this functions i, read-writing it */
    printf("x=%d, i=%d\n", x, i); /* reading */
}
上述函数中的
i
仅受
i++
(初始化为0除外)的影响,否则不会改变。但是,作为
静态的
,它会将函数的一次执行的值带到下一次执行,即初始化
=0
仅在第一次执行期间发生。 上面函数中的
x
携带下面函数中的
i
的值

void increase(int x)
{static int i=0; /* the only i seen inside this question */
    x = i + x; /* using this functions i, reading it */
    i++;       /* using this functions i, read-writing it */
    printf("x=%d, i=%d\n", x, i); /* reading */
}
下面的
i
函数通过循环计数,但不受其他任何地方的影响

int main(void)
{
    int i; /* the only i seen inside this question */
    for (i=0; i<4; i++) /* using this functions i, including to increment it */
        increase(i); /* handing it as parameter to function,
                        the value given is seen within the function as x */
    printf("i=%d\n", i); /* reading it for output */
    return 0;
}
int main(无效)
{
int i;/*我在这个问题中看到的唯一一个*/

对于(i=0;iHm…一次有点太多问题…按值调用与按引用调用、范围、
static
…也许最好一次问一个问题?两个i都不同,都是其功能块的局部问题。有两个i请将最佳答案标记为已接受。