2

I am having trouble getting a simple pass by reference to work the way I expect. Fist off, when I compile, I get the following warning:

warning: value computed is not used [-Wunused-value]

Second, I expect it to print a 2, not a 1 at the end of the program.

$ ./testAdd
1

Here is the simple code:

#include <stdio.h>

void addone(int *j) {
  *j++;
}

int main(int argc, char *argv[])
{
  int i = 1;

  addone(&i);

  printf("%d\n", i);

  return 0;
}

What is going wrong here?

2
  • @EdS. While, strictly speaking, C has no pass by reference, passing a pointer to a function and changing the value it references is effectively the same thing. See this answer as well.
    – Kninnug
    May 16, 2013 at 22:42
  • @Kninnug: No, it's not. You're adding a level of indirection, but you are always passing your arguments by value. May 17, 2013 at 15:47

1 Answer 1

9

Operator precedence. The increment operator binds more tightly than the dereference operator, so your code is semantically equivalent to:

*(j++)  // invalid read BTW

When you wanted

(*j)++

Also note that C has no notion of pass by reference; everything is pass by value. You're passing the address by value. Indirection != pass by reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.