Why is it different from putting a return value of a function directly in a c++ for statement conditional expression?

Asked 2 years ago, Updated 2 years ago, 49 views

#include <iostream>
using namespace std;

#define MAXN (100000)
int N;
int sol[MAXN + 10];
int wp, rp = 0;
int que[MAXN + 10];

void push(int d) {
    if (wp < MAXN) {
        que[wp] = d;
        ++wp;
    }
}
int front() {
    if (rp != wp) {
        int t = que[rp];
        ++rp;
        return t;
    }
}
bool empty() {
    if (rp == wp)
        return true;
    else
        return false;
}
int end() {
    if (!empty()) 
        return que[wp-1];
}


int main() {
    cin >> N;
    for (int i = 0; i < N; i++) 
        push(i+1);
    for (int j = 0; j < end() /2; j++) {
        push(front());
        cout<<"j"  << j <<endl;
    }
    cout << front() << "\n";
    return 0;
}

This code was operated by simply implementing the queue. If you run the code above and enter 4, it accumulates in the order of 1, 2, 3, and 4 in the queue, and you want to turn the for statement with /2 at the end value, but if you operate the end function, you get 4, but if you do end()/2, you get 1. Instead, if you put the value of end() in the variable t and t/2, you get 2 and turn the for door 2 so why is this?

The results of the above code are as follows. 4 -> Input j0 2

c++ for

2022-09-20 10:27

1 Answers

If you enter 4 to enter 1, 2, 3, and 4 in the queue, end() is 4, but when push(front(); is executed, the front() function subtracts the preceding 1 and then enters the queue. Therefore, the status of the queue is now 2, 3, 4, 1. If you read end() in this state, the return value is 1, and 1/2 is 0, so the for-loop condition when j is 1, becomes a false 1 < 0 and exits the for-loop.


2022-09-20 10:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.