C语言基础知识

时间:2015-10-01 14:58:45

标签: c

我在linux终端输入以下代码

#include <stdio.h>
int main(void)
{

    int a;
    a=1;
    printf("%d\n",a++);
}

现在输出显示为1而不是2.为什么它会增加 使用++运算符的a的值,但仍然存储在a中的值不会增加。请帮助。

2 个答案:

答案 0 :(得分:5)

a ++是后增量。因此,它首先分配使用它的位置的值,然后递增。

执行以下两个示例。你应该清楚地了解前后增量:

int main(void)
{
    int a, c;
    a = 1;
    c = a++; // assigns the value 1 to c and increments the value of a
    printf("a: %d and c: %d\n",a,c);
}

int main(void)
{
    int a, c;
    a = 1;
    c = ++a; // increments the value of a and then assigns it to c
    printf("a: %d and c: %d\n",a,c);
}

答案 1 :(得分:1)

在C中,后缀运算符printf("%d\n",a); a += 1; 在使用后增加变量的值。所以你的陈述相当于

++

您可以通过使用前缀printf("%d\n", ++a); 来实现您的行为:

a += 1;
printf("%d\n", a);

相当于:

awk 'BEGIN {str="hello bee"; patt="llo"; gsub(patt,"XX",str); print str}'
heXX bee
相关问题