Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does my code get a value for my variable? C++

I’m following this book called C++ Primer Fifth Edition and it had this code:

#include <iostream>

int main() {
    int currVal = 0;
    int val = 0;
    if (std::cin >> val){
        int cnt = 1;
        while (std::cin >> val){
                if (val == currVal){
                    ++cnt;
                }
                else {
                    std::cout << currVal << " occurs " << cnt << " times " << std::endl;
                    currVal = val;
                    cnt = 1;
                }


        }
        std::cout << currVal << " occurs " << cnt << " times " << std::endl;
    }
    return 0;
}

This code tells me how many times a number has occured in the users input.

What I don’t quite understand yet is how does the code know what the currVal is when I gave it a value of 0 and I haven’t told it anything about the current value except in the last else statement. My question is does the code run the else code first and then runs the if statement code? But then the cnt wouldn’t be able to count anything because it always gets reset to 1 at the end of the else statement. I know this is pretty basic but I just can’t figure out the answer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I couldn’t find an answer on google nor did it explain it in my book so I thought maybe I could ask it here.

>Solution :

No. The first time the if() statement is run, it checks against zero.

currVal will only be updated when the else is executed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading