-1

C passes values not arguments — that is what I am told, but how do I fix this? I just don't understand.

#include <stdio.h> /* This will not work */ void go_south_east(int lat, int lon) { lat = lat - 1; lon = lon + 1; } int main() { int latitude = 32; int longitude = -64; go_south_east(latitude, longitude); printf("Now at: [%i, %i]\n", latitude, longitude); printf("The log pointer is at %x\n", longitude); } 

It doesn't update the values in main() — they stay at 32, -64 but should be 31, -63.

3
  • 1
    Perhaps you mean "C passes by value not reference" ? Google that and you'll see many duplicates. Commented Oct 18, 2018 at 0:14
  • 1
    You'll need to pass the address of latitude and longitude to your function, and rewrite the function to take pointers, and to modify the values that the pointers point at. And if you're not sure how to do that, please consult your text book. Note that if you printed lat and lon in the go_south_east() function, you'd see that they changed value, but the variables are local to the function, and changes to them do not affect the values in the calling function (main()). Commented Oct 18, 2018 at 0:15
  • Look into these topics/concepts. Pointers, variable memory address, pass by value, pass by reference. Here's a good place to start. stackoverflow.com/questions/2229498/passing-by-reference-in-c Commented Oct 18, 2018 at 0:45

1 Answer 1

5

By default C will create a copy of the argument and operate on it inside the function, the copies cease to exist as soon as the function ends. What you want to do is use pointers in your arguments and dereference them to operate on the value the pointers point to.

This topic may help you understand better: What's the difference between passing by reference vs. passing by value?

This should work:

void go_south_east(int *lat, int *lon) { *lat = *lat - 1; *lon = *lon + 1; } int main() { int latitude = 32; int longitude = -64; go_south_east(&latitude, &longitude); printf("Now at: [%i, %i]\n", latitude, longitude); } 
Sign up to request clarification or add additional context in comments.

7 Comments

You meant *lat and *lon inside the function, didn't you?
I meant in the function body
Did you actually run your sample? If you did, you'd have the same results eitherway. The compiler interprets both writtings the same way.
my mistake, updated the code to a working version. Sorry @Pavel I misread, I thought you were talking about in the argument as my links pointed. You are right.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.