C:++ i和i ++有什么区别? [英] C: What is the difference between ++i and i++?

查看:102
本文介绍了C:++ i和i ++有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,使用++ii++有什么区别,应该在for循环的增量块中使用什么?

解决方案

  • ++i将增加i的值,然后返回增加的值.

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

  • i++将增加i的值,但是返回i保持之前的原始值.

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

对于for循环,两者均有效. ++i似乎更常见,也许是因为 K& R 中所使用的. >

在任何情况下,请遵循准则优先使用++i胜过i++",这样就不会出错.

关于++ii++的效率,有几条评论.在任何非学生项目的编译器中,都不会有性能差异.您可以通过查看生成的代码来验证这一点,该代码是相同的.

效率问题很有趣...这是我的一个答案: 在C中,i ++和++ i之间是否存在性能差异?

​​ @OnFreund 指出,对于C ++对象,它有所不同,因为operator++()是一个函数,并且编译器不知道如何优化临时对象的创建以保存中间值.

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

解决方案

  • ++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 @OnFreund 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.

这篇关于C:++ i和i ++有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆