Thread: Can somebody explain to me what is happening here?

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    36

    Can somebody explain to me what is happening here?

    Hi!

    Here is a small piece of code with the output:
    Can somebody explain to me what is happening here?-output-png

    I do understand that given the 2nd initialization (i = 1) , the following condition is not true and hence the program leaves the loop right away without printing out "ABC".

    But I do not understand why it would print out
    the first initialization (printf("Z")) ?

    Has someone an idea?


    Regards,
    Placebo

    edit: Please ignore the 2nd image - somehow I cannot remove it.
    Attached Images Attached Images Can somebody explain to me what is happening here?-output-png 
    Last edited by Placebo; 04-07-2019 at 03:35 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,272
    That's not an initialisation; that's a subexpression, the left hand side of a comma expression. So, of course it will be executed: control enters that part, and only exits the loop when it reaches the next part, i.e., the loop condition.

    Note that i = 1 is also not an initialisation: it is an assignment, although it does assign the initial value of i. If you wanted to initialise i, you would do that at the point of declaration.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Dec 2018
    Posts
    36
    Thanks, helps a lot.
    Just did not imagine for an unknown reason that expressions are getting executed when they appear within the brackets of a for-loop.
    But in hindsight, of course the expression must get executed, as same as the programm successively executes all other commands, such as value-assignements, increments, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-25-2017, 02:32 PM
  2. How come this is happening?
    By Angermanaged in forum C++ Programming
    Replies: 3
    Last Post: 03-21-2009, 07:35 PM
  3. What is happening here please explain
    By jayee_spicyguy in forum C Programming
    Replies: 5
    Last Post: 09-23-2008, 05:27 AM
  4. Explain me what is happening
    By capvirgo in forum C Programming
    Replies: 2
    Last Post: 02-18-2008, 08:26 AM

Tags for this Thread