C语言基础

标签 c

我在linux终端中输入以下代码

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

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

现在输出显示为 1 而不是 2。为什么我要递增 使用++ 运算符获取 a 的值,但 a 中存储的值仍然没有增加。请帮忙。

最佳答案

a++ 是后增量。因此,它首先在使用 a 的地方分配 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);
}

关于C语言基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32890758/

相关文章:

c - 字符串解析 - 在内存重新分配失败或程序结束后调用 free() 时程序崩溃。

c - 查找C中最大元素的位置,位置实例

c++ - 如何进行主动 sleep ?

c - 寻找有关 Linux 系统调用的详细文档

c - 在 Linux 中,这些 elf.h 对象是什么?

c - atoi() 从 char 数组返回 0

c - 使用 C + SWIG + 函数指针伪造面向对象?

无法在 Pelles C 上编译程序

c - 如何访问空字符之前的字符处的字符(字符串)数组

main 中的 C 函数错误 LNK2019