Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c - C:++ i和i ++有什么区别?(C: What is the difference between ++i and i++?)

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

  ask by The.Anti.9 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • ++i will increment the value of i , and then return the incremented value.

    (++i将递增的值i ,然后返回增加后的值。)

      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++将增加的价值i ,而是返回原来的价值i递增之前举行。)

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

For a for loop, either works.

(对于for循环,两者均有效。)

++i seems more common, perhaps because that is what is used in K&R .

(++i似乎更常见,也许是因为那是K&R中使用的 。)

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

(无论如何,请遵循“比i++更喜欢++i ”准则,这样就不会出错。)

There's a couple of comments regarding the efficiency of ++i and i++ .

(关于++ii++的效率,有几点评论。)

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?

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

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.

(正如On Freund所指出的,对于C ++对象而言,这是不同的,因为operator++()是一个函数,并且编译器无法知道优化临时对象的创建来保存中间值。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...