++ i和i ++有什么区别?

编程入门 行业动态 更新时间:2024-10-24 08:20:15
本文介绍了++ i和i ++有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在C中,使用 ++ i 和 i ++ 有什么区别,哪些应该用在$ for 循环的增量块?

解决方案

  • ++ i 将增加 i 的值,然后返回递增的值。 / p>

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

  • i ++ 会增加 i 的值,但返回原始值 i 然后递增。

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

  • 对于 for 循环,可以使用。 ++ i 似乎更常见,也许是因为这是 ++ i over i ++ ,你就不会出问题了。

    有几条关于 ++ i 和 i ++ 。在任何非学生项目编译器中,不会有性能差异。您可以通过查看生成的代码来验证这一点,这将是相同的。

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

    $ b

    作为Freund 笔记,对于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 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.

    更多推荐

    ++ i和i ++有什么区别?

    本文发布于:2023-07-29 08:59:47,感谢您对本站的认可!
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:有什么区别

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!