justin = { main feed , music , code , askjf , pubkey };
Ask Justin Frankel
No reasonable question unanswered since 2009!

Suggested topics: programming, music, sleep, coffee, etc.

Note: please do not ask questions about REAPER features, bugs or scheduling, use the forums instead.


Name: Ask: Human (enter yes):
[back to index] | [unreplied] | [replied] | [recent comments] | [all]

Question: There is while loop like this while (a<b); { //statements }. There is semicolon in while loop, terminating that loop, and the compiler completely ignores that loop. What is the usage of this? Can you give any example where this terminated loop is used?
Asked by Abhi (182.69.60.x) on September 6 2024, 8:16am
Reply on September 7 2024, 1:41am (edited at September 7 2024, 1:45am):
    so that semicolon terminates the while, so what you have is essentially this:
    while (a < b) { }
    { /* statements */ }
    
    which is probably not what you intended!

    But I see that you're saying the compiler ignores the loop. Well, if you have a loop that the compiler determines never exits, it is considered undefined behavior (UB) and for optimization purposes, since the loop has no side effects, the compiler is allowed to completely remove the loop.


Comments:
  • Posted by Don Speirs (98.97.118.x) on September 7 2024, 11:08pm:
    In a system where a and b might be dynamically changing from other processes - interrupt processes, other threads, or real world inputs I could MAYBE see this as useful. Probably better ways to do it though. And I would thinK a and b would have to be declared volatile to keep the compiler from optimizing it out

  • Posted by Justin on September 8 2024, 1:21am:
    yeah, volatile is the classic way to do it but these days you need something more like a memory barrier, which, depending on the architecture, might be required by the hardware itself.

  • Posted by Justin on September 8 2024, 1:21am:
    (x86 does not require it, though the compiler may...)

  • Posted by Justin on September 8 2024, 1:22am:
    also worth noting that locking a mutex implies a memory barrier (and the compiler won't optimize it out if the loop locks/unlocks a mutex)


Comment:
    Your Name:   -- Site Owner's Name:  (for human-verification)

    Comment:    

    
  
[back to index] | [unreplied] | [replied] | [recent comments] | [all]
Copyright 2024 Justin Frankel. | RSS