Reputation: 11
I'm getting started with C++ and I decided to do some random coding just for practice. So I was thinking of making a simple benchmarking program, here's how far I have gotten:
#include <iostream>
#include <ctime>
using namespace std;
int main(){
cout << "press any key to start benchmarking" << endl;
cin.get();
int pref_scorecounter = 0;
time_t pref_timestart = time(0);
do {
pref_scorecounter++;
time_t pref_timefinish = time(0);
int pref_timeduration = pref_timefinish - pref_timestart;
} while ( pref_timeduration < 5 );
cout << "Score: " << pref_scorecounter;
cin.get();
}
The way it works is that it shows how much times has the loop happened in 5 seconds. But I get this error:
error: 'pref_timeduration' was not declared in this scope
Any ideas why the variable defined in a loop doesn't work? Also why does this program not run at 100% cpu?
This project was ported from a PHP project I made a while ago and that PHP code works 100%, I tested with different servers and etc.
<?php
$pref_scorecounter = 0;
$pref_timestart = microtime(true);
do {
$pref_scorecounter++;
$pref_timefinish = microtime(true);
$pref_timeduration = $pref_timefinish - $pref_timestart;
} while($pref_timeduration < 5);
echo "Score: " . $pref_scorecounter;
?>
I can add some complex calculations later though...
Upvotes: 0
Views: 1644
Reputation: 1123
In a do-while statement, the body is executed before the condition is evaluated. But for what's in the body to work properly, including the declaration of pref_timeduration, the condition must be true. Bjarne Stroustrup recommends against the use of do-while loops.
Upvotes: 0
Reputation: 96258
The languages have different scoping rules.
In C++ the scope ends on closing bracket. If you want to use the variable in the condition, its definition has to be outside of loop scope.
Upvotes: 1
Reputation: 1469
Your problem is simple, it is related to the scope of the variable pref_timeduration
. You've declared the variable inside the loop while you're trying to access it outside. Initialize the variable outside the do {} while()
loop and update it inside the loop.
Upvotes: 0
Reputation: 234655
pref_timeduration
is defined within the scope block of the while
loop.
It therefore cannot be used in the loop exit test: while( pref_timeduration < 5)
is invalid and your compiler is telling you this.
One fix is to declare pref_timeduration
just before the do
. You can put an extra pair of braces around the whole thing if you're concerned about leaking the scope of pref_timeduration
to other parts of the function.
Upvotes: 0