+ 3

What effect does prefix increment operator do in increment expression of for loop?

Does it increases value of loop variable before execution of satements of loop?

1st Jul 2019, 2:35 PM
World Wide Knowledge
World Wide Knowledge - avatar
6 Respuestas
+ 2
Not really. for(int i=0; i<5; i++) does the same as for(int i=0; i<5; ++i). The is a difference if you do things in the increment expression. For example: for(int i=0; i<5; sum+=(i++)) sums up to 10 while for(int i=0; i<5; sum+=(++i)) sums up to 15
1st Jul 2019, 4:05 PM
daniel
daniel - avatar
+ 1
Prefix increment hits the increment operator first before the value then increments it immediately on the same statement ... Postfix increment hits the value first before the increment operator then increments it on the next statement.
1st Jul 2019, 9:03 PM
Franky BrainBox
Franky BrainBox - avatar
+ 1
No, the third part of a for loop is essentially the code that will execute after each loop iteration. Having i++ or ++i has no real difference because it is the same as adding the lines i++; or ++i; in code, you are not using the return type which is different, you are only using the value in i which has been increased by 1. Now, ++i is barely faster than i++ because i++ returns a temporary variable of the previous value, so it is better to use ++i where speed is needed, but in many cases i++ is more common and “more legible”
2nd Jul 2019, 3:38 PM
nk361
nk361 - avatar
0
It is a statement, that will be executed in the end of each iteration. int x = 0; for (cout << "1"; cout << "2"; cout << "3") { cout << "4"; x++; if (x > 3) {break;}} Output: 124324324324
1st Jul 2019, 3:20 PM
Seb TheS
Seb TheS - avatar
0
It depends on if you're running carrying out an operation on the same line
10th Jul 2019, 5:36 PM
Kingsley Wizard🇳🇬
Kingsley Wizard🇳🇬 - avatar
0
The expected output will be incorrect
7th Aug 2019, 1:59 PM
Nithish Nithish
Nithish Nithish - avatar