Thread: Best way to break out of loop

  1. #31
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    I don't see what's wrong with just looping some maximum number of times and then stopping. It limits the actual amount of computation to a fixed amount. This will correspond to a different amount of time on different systems, but does it matter?

    If you need to abandon processing until some event occurs, I do not see how you can avoid a call to WaitForSingleObject() or similar. It entails overhead, but what other choice do you have?
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  2. #32
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thanks for the comments!

    @iMalc "The fact that your real code will actually be doing something useful will mean that overall it wont be spending quite as much time sleeping."

    Yes i didnt realize that, my bad.

    @BMJ



    Code:
    void ShakeIt() 
    {
        RECT rcWndSz;
        int iX = 0;
        int iY = 0;
        int iScreenX = GetSystemMetrics(SM_CXSCREEN);
        int iScreenY = GetSystemMetrics(SM_CYSCREEN);
        
        DWORD oldtick = GetTickCount();
        while (1)
        {
            if (GetWindowRect(hWnd, &rcWndSz))
            {
                iX = rcWndSz.left + ((rand() % 5) * ((rand() % 100) > 50 ? 1 : -1));
                iY = rcWndSz.top  + ((rand() % 5) * ((rand() % 100) > 50 ? 1 : -1));
    
                iX = iX > iScreenX ? iScreenX : iX;
                iY = iY > iScreenY ? iScreenY : iY;
                iX = iX < 0 ? 0 : iX;
                iY = iY < 0 ? 0 : iY;
    
                SetWindowPos(hWnd, NULL, iX, iY, 0, 0, SWP_NOSIZE);
                Sleep(20);
            }
            
            if ((GetTickCount() - oldtick)> 3000) break;
        }
    }
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Number to Word (Billions)
    By myphilosofi in forum C Programming
    Replies: 34
    Last Post: 02-04-2009, 02:09 AM
  2. Looking for feedback on program segment
    By avron in forum C++ Programming
    Replies: 4
    Last Post: 05-07-2007, 04:38 PM
  3. Base converter libary
    By cdonlan in forum C++ Programming
    Replies: 22
    Last Post: 05-15-2005, 01:11 AM
  4. Keypress reading
    By geek@02 in forum Windows Programming
    Replies: 1
    Last Post: 06-16-2004, 12:16 PM
  5. error with code
    By duffy in forum C Programming
    Replies: 8
    Last Post: 10-22-2002, 09:45 PM