0
Using pointers instead of global variables
In one tutorial I heard that you can avoid global variables by using pointers. Can you give me some example?
6 Answers
+ 3
Yeah:
int foo(int* a){
(*a)++;
}
void main(){
int b=10;
foo(&b);
//prints 11
printf("%d",b);
}
Of course you could make b a global variable but it is not a good practice to have a lot of global vars. (btw I know c++ not C so I'm sorry if I made any minor mistake)
+ 1
xaralampis_ thank you, code is correct and compiles without errors, but had to sit and stare at it for a while :D
+ 1
Kry$tof no problem if you still are not sure about how it works I can explain it to you.
+ 1
xaralampis_ thanks it's ok I understand how it works
+ 1
Kry$tof yes of course you could do that but it doesn't make much sence. If instead of foo the function name was 'increment' for example writing this code would be bad because someone or if even you could do those mistake:
increment(c);//the function here basicly does nothing. the return value is not being used.
+ that the return value takes also space in memory for no reason.
+ that c does not actually increment, the parameter does.
What you are trying to understand here (I think) is "when to pass by pointer and when to pass by value?". My answer is that when you want to modify something you pass as a parameter, always try passing it by pointer. Otherwise return what you want using the return statement.
I don't get what you mean with your last question though.
0
@xaralampis_ Sorry for the late reply but isn't it easier to it like this? :
#include <stdio.h>
int foo(int c){
c++;
return c;
}
int main()
{
int c = 15;
printf("%i\n", foo(c));
return 0;
}
is there anything you cant do without pointers? thanks