Thread: Incrementing

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    30

    Incrementing

    Hello,

    Why is output [0 1] other than [1 1] ?
    Code:
    #include <stdio.h>int y=0;
     void f(int x)
     {
     	++x;
     	y++; 
     }
     main()
     {
     	int x=0;
    	f(x);
    	printf("%d %d", x, y);
    }

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Because you're incrementing a local copy, not the actual object that you're printing.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Registered User talahin's Avatar
    Join Date
    Feb 2015
    Posts
    51
    Why do you think it should be [1 1].

    Remember the x in void f(int x) is a local variable and has no meaning outside the function.

    if you want to return a value you can declare the function as returning an int type
    Code:
    int  f( int x)
    {
        ++x;
        y++;
        return x;
    }
    and in main do a call like
    Code:
    x = f( x );
    the other option is to use a reference like
    Code:
    void f( int * x)
    {
        ++(*x);
        y++;
    }
    and in main use
    Code:
    f( &x );

  4. #4
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    Thank you both, you made me clear in this point.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer Incrementing
    By zoowho in forum C Programming
    Replies: 4
    Last Post: 02-25-2010, 12:42 PM
  2. Incrementing Twice?
    By Kemaratu in forum C Programming
    Replies: 3
    Last Post: 09-27-2009, 11:13 PM
  3. incrementing in if statements?
    By tomisme in forum C Programming
    Replies: 6
    Last Post: 06-02-2008, 06:17 PM
  4. Incrementing along a vector
    By McFury in forum C++ Programming
    Replies: 2
    Last Post: 11-01-2006, 02:43 PM
  5. Incrementing by 2 not 1
    By Eckey in forum C++ Programming
    Replies: 6
    Last Post: 10-14-2004, 03:16 PM