Thread: Intersting Question

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    61

    Intersting Question

    Expression of if statement is a sequence point.

    Sequence point is a specified point in the execution sequence where all side effects of previousevaluations are complete and no side effects affects on all the subsequent evaluations.


    However, MS Visual Studio gives different answer in both the cases.

    Can any expert justify it who has knowledge in sequence point?

    Code:
    #include <stdio.h>
    int main()
    {
         int i=0;
         if ( --i ) // i is -1 now which is true
            printf(" One \n");
         else   
             printf("Two");
    
         return 0;
     }
    Output: One

    Code:
    #include <stdio.h>
    int main()
    {
         int i=0;
         if ( i-- ) //i should be -1  after evalueation if expression... but its remaining 0
                    // which is false
            printf(" One \n");
         else   
             printf("Two");
    
         return 0;
     }
    Output: Two

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    in the second case i is changed to -1 but the expression is evaluated before the change takes effect - and it evaluates to 0
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I am fairly sure this is not so much about sequence points as it is about the concept of pre- vs. post-operators. In x++, x is first evaluated, and then incremented. In ++x, it is incremented first, then evaluated. This happens for both conditionals and other forms of evaluation.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM