Home >Backend Development >C++ >The difference between ++i and i++ in c++

The difference between ++i and i++ in c++

下次还敢
下次还敢Original
2024-04-26 19:30:27865browse

In C, the difference between the increment operators i and i is the order of execution: i is incremented first and then the expression is evaluated, while i is first evaluated and then incremented. Therefore, use i when you need to use the incremented value immediately, and use i when you need to use the original value first and then increment it.

The difference between ++i and i++ in c++

The difference between i and i in C

In C, i and i are both increment operators, but they differ in the order of execution.

i: Prefix increment

  • The value of i will be incremented before calculating the expression .
  • Syntax: i
  • The following example increases the value of i by 1 and then prints the result:
<code class="cpp">int i = 10;
cout << ++i << endl; // 输出:11</code>

i : post-increment

  • Evaluates the expression first, and then increments the value of i.
  • Syntax: i
  • The following example prints the value of i and then increments it by 1:
<code class="cpp">int i = 10;
cout << i++ << endl; // 输出:10</code>

Summary

  • i Increments i before evaluating the expression.
  • i Increments i after evaluating the expression.
  • Use i when you need to increment i and use its new value immediately. Use i when you need to use the original value of i before incrementing it.

The above is the detailed content of The difference between ++i and i++ in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use cin in c++Next article:How to use cin in c++