can we declare like this how many times the loop executes while(flag)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thangam004
    New Member
    • Jun 2013
    • 1

    #1

    can we declare like this how many times the loop executes while(flag)

    flag=1;
    while(flag)
    {
    }
    if this is correct please explain me
  • stdq
    New Member
    • Apr 2013
    • 94

    #2
    Using the Open Watcom compiler, the above program worked fine, although it is necessary to declare (and initialize as done above) variable flag as being of a specific data type, for example as an integer:

    Code:
    int flag = 1;
    When the program reaches the while loop, the condition is evaluated to 1, which is true, and it never changes, because there is no statement inside the while that performs such change. Hence, the program loops infinitely.

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

      #3
      In the C language there is no predefined primitives for the boolean values true and false. Instead, the integer 0 is interpreted as false and any other integer is interpreted as true. So, if you have the above code (with stdq's modification) it should work nicely in any C compiler. It wouldn't just work with that value though; here are a few that would also work:
      Code:
      int flag = 42;
      while(flag) {}
      or
      Code:
      int flag = 1337;
      while(flag) {}
      Or try this:
      Code:
      int flag = ++9000;
      while(flag) {}
      It should work too.
      You can even go the other way around and actually calculate the result of an expression which you know will be true, such as
      Code:
      int flag = (7 == 7);
      while(flag) {}
      or
      Code:
      int flag = ! (1 > 2);
      while(flag) {}
      Here, true is always converted to 1 and false always to 0.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        When you ask if this is correct, what are your concerns? Have they been addressed by the preceding responses?

        Comment

        Working...