Reputation: 117
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?
Upvotes: 5
Views: 45308
Reputation: 174
Must try this code
#include <stdio.h>
int i=0;
void iprint()
{
i =i+1;
//printf("%d\n",i);
}
int main()
{
int j;
for (j=0; j<50; j++)
{
iprint();
printf("%d\n",i);
}
}
Upvotes: 0
Reputation: 71
Use a pointer to point to the global variable. Change the pointer value. Thats it
Upvotes: 7
Reputation: 736
you could have incremented the value of i in main function itself. By the way change the function to
int iprint(int i){
/*you have to mention the type of arguemnt and yes you have to return i, since i
variable in this function is local vaiable when you increment this i the value of
global variable i does not change.
*/
return i+1;
}
the statement
i=iprint(i); //this line updates the value of global i in main function
This happens like this because you are passing value in function by 'pass by value' method where a copy of variable is made. When you increment the i iprint method copy of global variable i is incremented. Global variable remains intact.
Upvotes: 0
Reputation: 33283
You don't need to pass global variables as parameters. If you declare a parameter or local variable with the same name as the global variable you will hide the global variable.
include <stdio.h>
void iprint();
int i=0;
int main()
{
int j;
for (j=0; j<50; j++)
{
iprint();
printf("%d\n",i);
}
}
void iprint()
{
i +=1; /* No local variable i is defined, so i refers to the global variable.
//printf("%d\n",i);
}
Upvotes: 2
Reputation: 409482
The problem with the first is that you pass the variable as an argument to the function, so when the function modifies the variable it's only modifying its own local copy and not the global variable. That is, the local variable i
shadows the global variable i
.
Not to mention that you don't actually declare the argument properly, so your program should not even compile.
Upvotes: 6