derek5. 2008-08-24 05:19 采纳率: 100%
浏览 493
已采纳

+ + i 和 i + + 的区别是什么?

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

转载于:https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i

  • 写回答

20条回答 默认 最新

  • 撒拉嘿哟木头 2008-08-24 05:23
    关注
    • ++i will increment the value of i, and then return the incremented value.

       i = 1;
       j = ++i;
       (i is 2, j is 2)
      
    • i++ will increment the value of i, but return the original value that i held before being incremented.

       i = 1;
       j = i++;
       (i is 2, j is 1)
      

    For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.

    In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

    There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.

    The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?

    As On Freund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(19条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害