I have a beginners C question. I want in the code below...
include <stdio.h>
void iprint();
int i=0;
int main()
{
int j;
for (j=0; j<50; j++)
{
iprint(i);
printf("%d\n",i);
}
}
void iprint(i)
{
i +=1;
//printf("%d\n",i);
}
... the function "iprint" to update the value of i each time is it called, e.g. update i so that it can be used in main with the value 1 for iteration 2, and 3 for iteration 2 etc.
I accomplished this by changing the code to this:
include <stdio.h>
int iprint();
int i=0;
int main()
{
int j;
for (j=0; j<50; j++)
{
i= iprint(i);
printf("%d\n",i);
}
}
int iprint(i)
{
i +=1;
//printf("%d\n",i);
return(i);
}
Do i have to return(i) to make that happen? The reason for asking, is that if i have a lot of functions using i, it's a bit annoying having to pass i between them. If you instead, somehow could update i like you update a global variable in matlab, that'd be great. Is it possible?
Global variables can be accessed and modified by any function in C. Global variables can only be defined before the main() function.
Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).
Introduction. We know that we can overwrite the value of local variables any number of times in a program. Similarly, we can also overwrite the value of global variables in a function.
If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g. This would change the value of the global variable to 55.
Use a pointer to point to the global variable. Change the pointer value. Thats it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With