Infinite Counter

Guys, I made an infinite counter. What is it useful for? Nothing.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	int numb;
	numb = 0;
	while (numb > -1) {
		cout << "The counter is at " << numb << "\n";
		numb = numb + 1;
	}
}

Just thought it was funny.
Last edited on
Some improvements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <limits>
#include<cmath> // not needed
using namespace std; // bad habit
int main()
{
	int numb; // not infinite, only 2147483647
	std::size_t number {}; // better variable name, don't unnecessarily abbreviate. Declare & initialise in 1 statement. brace initalise
	while (numb > -1) {
        while (number < std::numeric_limits<std::size_t>::max() )  // nearer to  infinite, program ends gracefully more than 5.8e13 years time
		std::cout << "The counter is at " << number << "\n";
		numb = numb + 1;
                number++;
	}
}
The standard library has an infinite counter: an unbounded std::ranges::iota_view
https://en.cppreference.com/w/cpp/ranges/iota_view


> an infinite counter. What is it useful for? Nothing.

An example of where it could be useful:
we want to generate the terms of an infinite series till the term converges to a limit.
Counters that run indefinitely are used to give a monotonic timestamp for an ongoing process.

Try this on for size:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::vector<std::uint64_t> counter(1, 0);
while (true){
    std::cout << "The counter is at ";
    for (size_t i = counter.size(); i--;)
        std::cout << counter[i] << " ";
    std::cout << std::endl;
    for (size_t i = 0; i < counter.size(); i++){
        counter[i]++;
        if (counter[i])
            break;
        if (i == counter.size() - 1)
            counter.push_back(0);
    }
}
Last edited on
Topic archived. No new replies allowed.