-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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Perhaps you mean "C passes by value not reference" ? Google that and you'll see many duplicates. – John3136 Oct 18 '18 at 00: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()`). – Jonathan Leffler Oct 18 '18 at 00:15
  • Look into these topics/concepts. Pointers, variable memory address, pass by value, pass by reference. Here's a good place to start. https://stackoverflow.com/questions/2229498/passing-by-reference-in-c – sellc Oct 18 '18 at 00:45

1 Answers1

4

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);
}
Ahmed Aboumalek
  • 613
  • 4
  • 21