or
if(whatever)
sleep(forsometime); //wait, doing 'nothing' for a time period, but it technically is doing a little bit under the hood
The compiler is almost always smart enough to remove do-nothing code. Sleep won't be removed, but empty ; statements or functions that have no side effects may be. Empty loops usually modify the loop variable somewhere and remain.
> Empty loops usually modify the loop variable somewhere and remain.
They remain only if modifying the loop variable is part of the observable behaviour of the program: for instance, if it is declared as volatile or if it is atomic (potentially shared across threads)
void do_nothing() { for( int i = 0 ; i < 1'000'000 ; ++i ) ; }
void do_nothing_a_million_times()
{
for( int i = 0 ; i < 1'000'000 ; ++i ) do_nothing() ;
}
void do_nothing_a_billion_times()
{
for( int i = 0 ; i < 1'000'000 ; ++i ) do_nothing_a_million_times() ;
}
int foo()
{
// do nothing a million billion times
for( int i = 0 ; i < 1'000'000 ; ++i ) do_nothing_a_billion_times() ; // optimised away
return 87 ; // code is generated only for this line
/*
mov eax, 87
ret
*/
}
Right. I would think it also stays if int i were outside the loop and used elsewhere in the code block:
for(i = 0; i < 10; i++) ;
cout << i; //loop stays, as far as I know, or at least some code will be inserted for it, as per the 'observable code' comment. I don't know if it will stay if I were not used again, though.
If int i were outside the loop and used elsewhere in the code block, and constant-folding couldn't be applied,
or if int i were at namespace scope and could later be used somewhere else in the program,
for( i = 0; i < 10; i++ ) ; would be rewritten as i = 10 ;