my function increment does not print 6 when called 3 times using a global variable

81 Views Asked by At

I have a header called "counter.h":

#ifndef REMAINDER_COUNTER_H
#define REMAINDER_COUNTER_H

extern int count;
int read();
int increment();
int decrement();


#endif //REMAINDER_COUNTER_H

the c++ file called counter.cpp:

int count;

int read(){
    return count;
}

int increment(){
    if (count < 5)
        count++;
    return count;
}

int decrement(){
    if (count > 0)
        count--;
    return count;
}

and the main file called "mainxc.cpp":

#include <iostream>
#include "counter.h"


int main(){
    count = 2;
    for (int i = count; i <= 6; i+=2)
        increment();
    std::cout << read();
}

I am trying to get 6 by only using the function read() 3 times but it does not print 6 but 5. Why is that?

1

There are 1 best solutions below

4
Pepijn Kramer On

Here is an example of a class :

#include <iostream>

// You have an invariant in your code 0 <= m_count <= 5
// in C++ that means : wrap it in a class (one of the main
// responsibility of classes is to safeguard invariants)

class counter_t
{
public:
    int increment()
    {
        if (m_count < 5) 
        {
            ++m_count;
        }

        return m_count;
    }

    int decrement()
    {
        if (m_count > 0) 
        {
            --m_count;
        }

        return m_count;
    }

    int get() // kind of convention to call readouts get (or get_count);
    {
        return m_count;
    }

private:
    int m_count{ 0 }; // Initializes m_count to 0
};

int main()
{
    counter_t counter;
    for(int n=0; n < 7; ++n) // convention is to use `<` instead of `<=`
    {
        counter.increment();
    }

    std::cout << counter.get();

    return 0;
}