I
I
Ivan Ivanov2014-03-09 09:11:14
Mathematics
Ivan Ivanov, 2014-03-09 09:11:14

Why doesn't the for loop decrement the value in prefix form?

Why does such a loop for(int i = f; i > 0; --i)not reduce the value ito 1 loop pass, although it is in prefix form?
The decrement only fires after the loop has been passed 1 time.
PS the task was about factorial, I solved it like this for(int i = (f-1); i > 0; i--), but I'm still interested - the previous version should have worked too

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
EXL, 2014-03-09
@Csklassami

1. In the for loop, there is no difference between the postfix or prefix decrement/increment form for the counter variable.
2. The first pass of the loop is carried out with the initial value i. Then the counter variable changes and the second pass of the loop will already have the value i1, and so on.
3. In your case, everything was done correctly:

exl@exl-Lenovo-G560e:~/SandBox > cat test.cpp 
#include <iostream>

int main() {
    int f = 15;
    for(int i = --f; i > 0; --i)
        std::cout << i << " ";
    std::cout << std::endl;
    return 0;
}

exl@exl-Lenovo-G560e:~/SandBox > g++ test.cpp
exl@exl-Lenovo-G560e:~/SandBox > ./a.out 
14 13 12 11 10 9 8 7 6 5 4 3 2 1

Note that for the value with which we will initialize the counter variable, there is a difference in decrement / increment:
exl@exl-Lenovo-G560e:~/SandBox > cat test.cpp 
#include <iostream>

int main() {
    int f = 15;
    for(int i = f--; i > 0; --i)
        std::cout << i << " ";
    std::cout << std::endl;
    return 0;
}
exl@exl-Lenovo-G560e:~/SandBox > g++ test.cpp 
exl@exl-Lenovo-G560e:~/SandBox > ./a.out 
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

V
Vampiro, 2014-03-09
@Vampiro

any operand that you supply as the third argument will be executed at the very end of the loop.

R
Rsa97, 2014-03-09
@Rsa97

for(int i = f; i > 0; --i)usually expanded by the compiler in

{
    int i = f;
    goto loop_cond;
loop:
    // тело цикла
    --i;
loop_cond:
    if (!(i > 0)) goto loop;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question