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?

Ed S.
  • 122,712
  • 22
  • 185
  • 265
Acroyear
  • 1,354
  • 3
  • 22
  • 37
  • @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](http://stackoverflow.com/questions/2229498/passing-by-reference-in-c/2229510#2229510) as well. – Kninnug May 16 '13 at 22:42
  • @Kninnug: No, it's not. You're adding a level of indirection, but you are *always* passing your arguments by value. – Ed S. May 17 '13 at 15:47

1 Answers1

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.

Ed S.
  • 122,712
  • 22
  • 185
  • 265