0

Why is this not working. I Just want loading like effects. I just compiled the code the g++ compiler. It take time and just print * * * B R E A K * * *. There is no difference between per letter.

#include <iostream>
using namespace std;

int main()
{
    int wait = 1000000000;
    char text[] = {"* * * B R E A K * * *"};

    for(int i = 0; i < 21; i++)
    {
        cout << text[i];

        for(int j = 0; j < wait; j++)
            ;
    }
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
deaddroid
  • 410
  • 2
  • 12
  • 1
    Why do you expect that there will be "difference between per letter"? – Soren Aug 25 '15 at 14:30
  • 1
    It appears to work as designed. What are you trying to do differently? – Bob Dylan Aug 25 '15 at 14:31
  • 2
    You can't rely on the second loop waiting at all, the whole thing could be optimized out. – TartanLlama Aug 25 '15 at 14:32
  • Use some sort of timer to do the pause, the empty loop can be completely optimized out by an optimizing compiler. Also prefer `std::string` over `char text[]`, it will make your life a lot easier. – shuttle87 Aug 25 '15 at 14:34
  • possible duplicate of [Sleep for milliseconds](http://stackoverflow.com/questions/4184468/sleep-for-milliseconds) – Bernhard Barker Aug 25 '15 at 14:34
  • I am just new to c++ but can you explain what " optimized out by an optimizing compiler " means?. Thanks in advance.. – deaddroid Aug 25 '15 at 15:27
  • When your compiler runs over your code, it looks for opportunities to make your program run faster. When it sees your loop, it notices that it doesn't matter and excludes it from the compilation process. – Nimelrian Aug 25 '15 at 15:40

1 Answers1

6

Your wait loop is likely optimized out from the code because the compiler can see that it has no effect. Try to do a nano-sleep instead, like

#include <iostream>
#include <unistd.h>

using namespace std; 
int main()
{
   char text[]={"* * * B R E A K * * *"};
   for(int i=0;i<21;i++)
   {
      cerr<<text[i];
      usleep(100000);
   }
}

Also, std::cout is buffered, which means that it will not write until there is a newline, program terminates or you flush -- for simplicity change the cout to cerr which is non-buffered....

Soren
  • 14,402
  • 4
  • 41
  • 67