Thread: Simple pointer to function

  1. #1
    Registered User
    Join Date
    Mar 2010

    Simple pointer to function

    I have this short program

    #include <stdio.h>
    void passByReference(int *x);
    int main(int argc, char **argv) {
        int value = 10;
        printf("before = %d\n", 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
    An expression doing subtraction creates a temporary. What you need to do is perform the subtraction, then pass it.
    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).
    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, Buttercup, 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, 08:17 AM
  2. Replies: 3
    Last Post: 03-13-2012, 12: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, 12:46 PM
  5. Replies: 9
    Last Post: 01-02-2007, 04:22 PM