Thread: What's the difference between var++ and ++var . revisited

  1. #1
    Registered User
    Join Date
    Aug 2017
    Posts
    1

    What's the difference between var++ and ++var . revisited

    In 2007, the original title, without "revisited", was posted on this forum.
    It was only a two line program, initializing x, and then printing it using either x++ or ++x. I believed there should have been a third line to show what x becomes after line 2. Here's my sample program:

    Code:
        #include <stdio.h>
        int main (void)
        {  int x;
           x = 0;
           printf("1: First x:   X = %d\n" , x);
           printf("2: Using x++, X = %d\n" , x++);
           printf("3: Final x:   X = %d\n" , x);
           x = 0;
           printf("1: First x:   X = %d\n" , x);
           printf("2: Using ++x, X = %d\n" , ++x);
           printf("3: Final x:   X = %d\n" , x);
           return(0);
        }
    And here is the result:

    1: First x: X = 0
    2: Using x++, X = 0
    3: Final x: X = 1
    1: First x: X = 0
    2: Using ++x, X = 1
    3: Final x: X = 1

    Now it's clear that x transitions from 0 to 1 in both cases.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,616
    It's important to remember that expressions as function arguments are evaluated before the function is entered, so you aren't really using the return value for x++ or ++x. Whereas if you use the x++ or ++x in other places, it will make a difference.

    Like for example this implementation of strncpy:
    Code:
    char * strncpy(char *a, char *b, size_t n) {
        char *rv = a;
        while (n-- > 0 && *b != '\0') {
            *a++ = *b++;
        }
        while (n > 0) { /* technically strncpy pads longer buffers with \0 */
            *a++ = '\0';
            --n;
        }
        return rv;
    }
    Last edited by whiteflags; 08-29-2017 at 10:52 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. iteration revisited
    By robwhit in forum C Programming
    Replies: 3
    Last Post: 09-05-2007, 09:38 AM
  2. nop - revisited
    By oioi in forum Tech Board
    Replies: 4
    Last Post: 12-28-2004, 10:18 AM
  3. VSD revisited
    By VirtualAce in forum Game Programming
    Replies: 0
    Last Post: 05-01-2004, 04:27 PM
  4. windows GUI revisited
    By Spectrum48k in forum C Programming
    Replies: 2
    Last Post: 06-02-2002, 05:11 PM
  5. Americanisations revisited.
    By Brian in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 03-06-2002, 12:03 PM

Tags for this Thread