Function that does absolutely nothing ?

Is there a function that does absolutely nothing in c++ ? I want to make something like :

c=_getch();
if (c=='1')
{
do x;
}
if (c=='2')
{
do nothing;
}

Please don't tell me to use a while loop or the else function. I need to know if there is a special do nothing function.
#include <thread>

// does absolutely nothing nothing in this program
std:: this_thread::yield() ;
thanks
Have you checked what happens if you leave your ‘if’ statements empty?
1
2
3
4
5
6
7
8
#include <iostream>

int main() {
    char c = '2';
    if(c == '1') {}
    if(c == '2') {}
    return 0;
}

; does nothing also.

so

if(whatever)
; //do nothing

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.



Last edited on
> 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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 
    */
}

https://godbolt.org/g/JNH84D
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.






Last edited on
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 ;
Topic archived. No new replies allowed.