Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a global variable in C

Tags:

c

scope

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?

like image 905
user2466382 Avatar asked Sep 23 '13 10:09

user2466382


People also ask

Can you update a global variable in C?

Global variables can be accessed and modified by any function in C. Global variables can only be defined before the main() function.

Can you update a global variable?

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).

Can global variables be overwritten?

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.

How do you change a global variable 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.


1 Answers

Use a pointer to point to the global variable. Change the pointer value. Thats it

like image 118
Vamsavardhana Vijay Avatar answered Oct 26 '22 01:10

Vamsavardhana Vijay