Why would you use pointers to update variables instead of global variables? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

Why would you use pointers to update variables instead of global variables?

I'm trying to decipher some old code in C++ (which I barely know any of) to translate it into another langauge and the author used pointers frequently. A common use was in inputs to functions, they inputted say &my_var to point to the memory address of my_var so they could change it within the function without having to return the new value. Is there any benefit to using pointers to update variables rather than declare them as global variables? Also, is there any reason why you wouldn't just input and output these variables in each function they're used in?

17th Oct 2018, 12:26 AM
Jessica Wilson
Jessica Wilson - avatar
2 Réponses
+ 4
Global variables are often considered bad practice 'cause they make the code tight-coupled and bring out side effects. A function is supposed to work independently and be reuseable, and client code should be able to make out what a function does without looking into the source code. Passing and returning by value are costly if your argument is a huge chunk of memory, considering that every call to the function must make a copy of that argument. Using pointers/references is more efficient in this case.
17th Oct 2018, 1:03 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 1
Everything matters in Programming. Pointers works directly with memory address. If you are Using Global variable than you can't use the same name for another variable which sometime causes problem
17th Oct 2018, 6:00 AM
Raziul Islam
Raziul Islam - avatar