1

I want to learn how to make compact switches, tell me if I'm doing it right or can I simplify it?

    auto _time = 5s;
    bool save_time;
    auto fs_time = steady_clock::now();

    for(;;) {
    auto now_time = steady_clock::now();

    if (duration_cast<seconds>(now_time - fs_time) >= _time) {
       save_time = true;
    }
    else {
       save_time = false;
    }

    // CODE ....

     if(save_time) {
     // CODE ....

     }
     if(save_time) {
     // CODE 2 ....

     }
    }

I do this to not write the same thing repeatedly.

    if (duration_cast<seconds>(now_time - fs_time) >= _time) {}

Perhaps this slows down the code when it checks it constantly.

menfix
  • 61
  • 7
  • 1
    The question is completely unclear. What to you mean by compact switches? Or what do you mean by "switch" in general? – A M Mar 21 '20 at 08:53

1 Answers1

4

Compact means in one line?

save_time = (duration_cast<std::chrono::seconds>(now_time - fs_time) >= _time) ? true  : false;

Or even more compact as Default suggested:

save_time = (duration_cast<std::chrono::seconds>(now_time - fs_time) >= _time);

Regarding the use of using, have a look to this question: Why is "using namespace std;" considered bad practice?

Jose
  • 3,306
  • 1
  • 17
  • 22