Search code examples
c++c

how to compiler compile if statement


main()    
{

   int k = 5;

    if(++k <5 && k++/5 || ++k<=8);  // how to compiler compile this statement 
  print f("%d",k);
}

// Here answer is 7 but why ?


Solution

  • In following:

    for && "something" is evaluated when first condition is True

    for || "something" is evaluated when first condition is False

    ( (++k <5)      &&          (k++/5) )      ||      (++k<=8)
    
    ( 6 < 5         AND        something )     OR   something
    
    ( False         AND        something )     OR   something
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    False                      OR   7 < 8
    
                    False                      OR   True
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                
                                              True
    

    So k comes out to be 7