Thread: For Loop and Post Increment Debacle

  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    3

    For Loop and Post Increment Debacle



    I am not understanding what the output to this for loop is p=2 and q=3.

    Here is my reasoning, if a kind person can point to where I am wrong.

    Code:
    main(){
    	int p, q;
    	for (p = q = 0; p < 3; p++)
    	{
    		q += p;
    		printf("%d", q);
    		system("pause");
    	}
    }
    Trace:

    p=0 --> initial value
    q=0 --> initial value
    0<3 is TRUE --> evaluation
    OUTPUT: q=0 -->execution
    p=0 --> update
    0<3 is TRUE --> evaluation
    p=1 --> post increment update
    OUTPUT: q=1 --> execution
    p=1 -->update
    1<3 is TRUE -->evaluation
    p=2 -->post increment update
    OUTPUT: q=3 --> execution
    p=2 --> update
    2<3 is TRUE --> evaluation
    p=3 --> post increment update
    OUTPUT: q=6 -->execution
    p=3 -->update
    3<3 is False -->evaluation
    Terminate program

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Code:
    for ( init ; condition ; step ) {
      action;
    }
    init happens once only
    condition is evaluated
    - if true, the loop action executes, followed by step.
    - if false, the loop exits.

    Basically, condition + action + step happen in sequence until condition is false.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with Pre and Post Increment !
    By thebenman in forum C Programming
    Replies: 25
    Last Post: 10-30-2014, 01:05 AM
  2. Post and Pre Increment
    By Raj 89 in forum C Programming
    Replies: 7
    Last Post: 11-22-2012, 11:02 PM
  3. Post Increment an Pre Increment operators in c++
    By anil_ in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2011, 08:27 PM
  4. pre & post increment need help
    By zing_foru in forum C Programming
    Replies: 6
    Last Post: 10-09-2009, 12:14 PM
  5. Post increment and pre increment help
    By noob2c in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2003, 03:03 AM

Tags for this Thread