Why does a variable passed to function not keep the changed value when it exits the function?

Asked

Viewed 88 times

-2

I want the variables latitude and longitude to be updated, but only the variables lon and lat are being changed. I cannot add latitude = latitude - 1 or longitude= longitude + 1.

Print do meu terminal no Code Blocks

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

You are passing variables by reference when using the &, so it’s not passing a value, it’s passing the address where it has a value. You can read more about it at What is the meaning of the operator "&" (and commercial) in the C language?.

In the function definition you are receiving normal values with the type int. When you call the function you pass an address, the value your function is receiving is the address of a variable, so when you manipulate the value is changing the address set there and nothing else, which will have an innocuous action.

If you need to pass an address you should receive an address. And to say that you have to use the type int * (or another type of point to a value of another type), it may not be just the basic type, it has to be a pointer to the type.

It is not enough to change the parameter, you have to do this in all access to the variable because you want access to the value and not the address. Remember that this variable is always the address and is not what you want to manipulate, for example *lat. Done this you change the value you want.

I would show with an example, but as the AP did not make it easy for us and I would have to type all the code for this, there will be only the explanation. The answers can’t be as good when the questions haven’t been asked better.

  • I think I got it, in the function parameter I passed only the variable address, so the void function will receive this address, so this will only change the address value. But, because the output immediately gave the value of latitude and longitude without change?

  • It’s in the answer, you changed the address and that’s innocuous in that code.

  • but why innocuous? There was to appear a value equivalent to the position of the discrete variable?

  • It’s in the answer, you’re going through the address and not the value, so the value is not being changed.

  • Change the parameters of your function to (int * lat, int * lon) and operations to *lat -= 1; and *lon += 1; and evaluate the results. Then study the difference in passing parameters when you pass a value and when you pass an address.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.