Thread: Need help with operators

  1. #1
    Registered User
    Join Date
    Jun 2020
    Posts
    2

    Need help with operators

    Hi!
    I'm pretty new to c programming (and to programming itself) and I've stumbled upon something I don't really understand about the ++ operator.

    Code:
    int z, p;
    z = 6;
    p = z++;
    
    printf("%d %d", z, p);      //output: "7 6".
    As far as I understand, ++ means add 1, so z++ means z = z+1, which in this case would be z = 6 + 1 = 7.
    Now, when I see p = z++, I read it as: p = z = z + 1. Now, since the left value of an equation is assigned the right value, I assume that the new z equals 7 and p equals z, so also 7. However, printf shows p as 6 and not 7. So I really don't understand why p is assigned the old value of z (6) and not the new value (7)?

    Can anyone explain?
    Thanks!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Recall that z++ is post-increment, i.e., the increment is only applied after the current value of z is used in the expression. If you use pre-increment instead with ++z, you would then get the behaviour you expected as the increment would be applied before the value is used in the rest of the expression.
    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
    Jun 2020
    Posts
    2
    Hey got it, thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 04-01-2014, 04:45 AM
  2. C operators.
    By JOZZY& Wakko in forum C Programming
    Replies: 1
    Last Post: 11-24-2009, 02:01 PM
  3. operators... which gets run first?
    By Verdagon in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2005, 08:23 PM
  4. operators???
    By arjunajay in forum C++ Programming
    Replies: 11
    Last Post: 06-25-2005, 04:37 AM
  5. operators in c++
    By condorx in forum C++ Programming
    Replies: 1
    Last Post: 09-05-2002, 07:43 AM

Tags for this Thread