Simple pointer to function

This is a discussion on Simple pointer to function within the C Programming forums, part of the General Programming Boards category; I have this short program Code: #include <stdio.h> void passByReference(int *x); int main(int argc, char **argv) { int value = ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174

    Simple pointer to function

    I have this short program

    Code:
    #include <stdio.h>
    
    void passByReference(int *x);
    
    int main(int argc, char **argv) {
        int value = 10;
        printf("before = %d\n", value);
        passByReference(&value);
        printf("after = %d\n", value);
    
        return 0;
    }
    
    void passByReference(int *x) {
        *x *= 3;
    }
    Which works as expected, the output is

    before = 10
    after = 30
    But I can't figure out how to pass in value - 1 = 9, into the function. I've tried both &(value-1) and &value-1 and neither work.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,679
    An expression doing subtraction creates a temporary. What you need to do is perform the subtraction, then pass it.
    Code:
        --value;
        passByReference(&value);
    You can combine the two expressions into one, but that is not a really good idea, as it makes things less clear (multiple side-effects on one variable in an expression are harder to get right, and it is easy to end up in the realm of undefined behaviour).
    Code:
       passByReference(&(--value));
    Either way, you're decrementing the value of the variable, but still passing the same address.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function pointer and Member function pointer usage?
    By freiza in forum C++ Programming
    Replies: 4
    Last Post: 05-30-2012, 09:17 AM
  2. Replies: 3
    Last Post: 03-13-2012, 01:15 PM
  3. Need help with simple function pointer
    By livin in forum C Programming
    Replies: 1
    Last Post: 12-01-2011, 09:00 PM
  4. Replies: 7
    Last Post: 07-04-2007, 01:46 PM
  5. Replies: 9
    Last Post: 01-02-2007, 04:22 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21