You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于++自增运算符的困惑:如何让c保持4、d变为5?

问题描述

想要实现变量c的值保持为4,变量d通过c的自增操作变为5。但当前用C语言前置自增运算符写的代码运行后,c和d都变成了5,不符合预期。要求必须用++运算符而非+1实现,类似参考的Bash脚本逻辑。

当前C语言代码

#include <stdio.h>

int main()
{
int c = 4;
int d = ++c ;
printf("Value of c is: %d \n", c);
printf("Value of d is: %d \n", d);
}

当前输出

Value of c is: 5 
Value of d is: 5 

期望输出

Value of c is: 4
Value of d is: 5 

参考Bash脚本

#!/bin/bash
c=4

echo "C is now $c"

d=$((++c))

echo "D is now $d"
解决建议

C语言里的++运算符不管前置还是后置,本质都会修改原变量的值——这和Bash的行为不一样,Bash是先输出c再执行自增,而你要的是c保持原值、d得到c+1且用++实现,可按以下两种方式处理:

  • 方法1:先赋值给d再自增
    先把c的初始值赋给d,再对d执行自增操作,这样c不受影响,d刚好变成5:

    #include <stdio.h>
    
    int main()
    {
        int c = 4;
        int d = c;
        d++; // 用++d也可以,这里效果完全一致
        printf("Value of c is: %d\n", c);
        printf("Value of d is: %d\n", d);
    }
    
  • 方法2:临时变量还原c的值
    如果一定要通过操作c的自增来得到d,可以先把c的初始值存在临时变量里,对c自增后赋值给d,最后再把临时变量的值放回c:

    #include <stdio.h>
    
    int main()
    {
        int c = 4;
        int temp = c;
        int d = ++c;
        c = temp; // 把c还原为初始的4
        printf("Value of c is: %d\n", c);
        printf("Value of d is: %d\n", d);
    }
    

注意:C语言的++运算符设计目的就是修改原变量,所以要保留原变量的值,必须做额外的保存或赋值操作,这是和Bash语法的核心差异。

内容的提问来源于stack exchange,提问作者elbarna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:09:57