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

Answer from Vamsavardhana Vijay on Stack Overflow
🌐
IncludeHelp
includehelp.com › code-snippets › c-program-to-define-modify-and-access-a-global-variable.aspx
C program to define, modify and access a global variable
Value will be printed into main() then we are modifying the value of x with 200, printing the value and again modifying the value of x with 300 through the function modify_x() and printing the final value. Here modify_x() is a user defined function that will modify the value of x (global variable), ...
Discussions

How do you update a global variable in c?
You change a global variable the same way you change any other variable int g_my_global = 0; void func() { g_my_global = 10; } int main() { func(); printf("%d",g_my_global); return 0; } will print 10 More on reddit.com
🌐 r/C_Programming
32
0
September 4, 2016
Changing a global variable's value with a function with the variable passed as an argument
I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return num; } · I get 55 back when I input a as an argument, but globally, a is still ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 30, 2020
How can you modify global variables that are used in functions that are being called with ccall?
From the documentation, I got that it’s possible to retrieve pointers to global variables by using the cglobal function. However, I wasn’t able to figure out from that how I can set the value of a global variable that is being used in a function that I am calling via ccall, or how I can ... More on discourse.julialang.org
🌐 discourse.julialang.org
1
0
January 27, 2023
Global Variables - With Fucntions.

Example for global variables

global MyVar := 1337

MsgBox % MyFunc("Leet")


MyFunc(string)
{
    return string " = " MyVar
}

or

MyVar := 1337

MsgBox % MyFunc("Leet")


MyFunc(string)
{
    global MyVar
    return string " = " MyVar
}
More on reddit.com
🌐 r/AutoHotkey
6
1
August 17, 2017
🌐
Quora
quora.com › Is-there-any-way-in-c-to-change-the-value-of-a-global-variable-through-a-function-without-passing-it-to-the-function
Is there any way in c to change the value of a global variable through a function without passing it to the function? - Quora
Answer (1 of 5): A global variable’s value can be changed through a function without passing it as an argument. That’s why they are commonly used in the first place :- See the following :- [code]#include %d\n", c); ...
🌐
Reddit
reddit.com › r/c_programming › how do you update a global variable in c?
r/C_Programming on Reddit: How do you update a global variable in c?
September 4, 2016 -

I used to know how to do this, but I've forgotten. I am currently working with a little terminal based game project of mine that requires that global variables be changed so they can be called by multiple functions, and sometimes modified in those functions for later use by one or more functions.

How do you change a global variable?

Edit 2: I solved my problem using pointers. For anyone wondering how to change a global variable (globally), you can use pointers.

Thanks for all the help everyone.

EDIT: Someone asked for the code, so I am including it here. The global variable I need is for the positionx and positiony variables. I am making a little mario type platformer game in terminal and I want to track the position in the 2d space using x and y positions that regularly get updated by different functions.

Right now the problem is the function gravity and the function movement are using two different version of the variables instead of the same one.

I used an array to store the data because I thought I was being clever and that would change the variable globally, but nope it still only does it locally.

Here is the code:


//START OF CODE

include <cs50.h>

include <stdio.h>

include <stdlib.h>

include <unistd.h>

int world[100][119]; int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int o = 0;
int p = 0;
int q = 0;
int r = 0;
int length = 30;
int height = 119;
int lengthinitialized = 99;
int heightinitialized = 119;
int worldpositionx = 0;
int worldpositiony = 0;
//use an array to track position as it alters a referencable number in a global way
int globalxy[2][2];
//use array to track movements
int movement[1][1];
//win condition has to equal 1 to stop
int won[1][1];

//void draw(void);
void populateboard(void);
void placelimits(void);
void placeobjects(void);
void draw(void);
void initializeplayer(void);
void gravity(void);
void move(void);
void instructions(void);
//void clear(void);

int main(void)
{ won[0][0] = 0;

populateboard();
placelimits();
placeobjects();
initializeplayer();
draw();

while(won[0][0] != 1)
{
    worldpositiony = globalxy[0][1];
    worldpositionx = globalxy[1][0];
    
    if(world[worldpositionx+1][worldpositiony] == 0)
    {
        while(world[worldpositionx+1][worldpositiony] == 0)
        //for(i=0;i&lt;20;i++)
        {
          gravity();
        }
    }
    
    draw();
    instructions();
    move();
    
}

}

void draw(void)
{
//Orignal draw before limited scope
for(m=0;m<length ;m++)
{
if(world[m][n]==0) { printf(" "); } else { printf("%i", world[m][n]); }

    for(n=0;n&lt;height ;n++)
        {
            if(world[m][n]==0)
            {
                printf(" ");
            }
            else
            {
                printf("%i", world[m][n]);
            }
        }
    
    printf("\n");
}

}

// **/

void populateboard(void) { for(i=0;i<lengthinitialized;i++) { for(j=0;j<heightinitialized;j++) { world[i][j] = 0; }

}


/**
 * 0s represent air
 * 1s represent solid objects
 **/

}

void placelimits(void) { //Boundaries are 10 layers thick to accomodate draw distance of 10. for(k=0;l<height; l++) { for(q=0; q<10;q++) { world[q][l] = 1; world[(length -1) - q][l]= 1; } }

for(l=0;k&lt;length;k++)
{
    for(r=0;r&lt;10;r++)
    {
     world[k][(height -1) - r] = 1;
     world[k][r] = 1;
    }
}
/**
 * 0s represent air
 * 1s represent solid objects
 **/

}

void placeobjects(void) { //test object for(o = 1; o<4; o++) { world[(o * 20)][5] = 1;

    world[(o * 20)+1][5] = 1;
    world[(o * 20)-1][5] = 1;
    
    world[(o * 20)][6] = 1;
    world[(o * 20)][4] = 1;
    
}

}

void initializeplayer(void) { world[15][15] = 2; worldpositionx = 15; worldpositiony = 15; globalxy[0][1] = worldpositiony; globalxy[1][0] = worldpositionx;

}

void gravity(void) { //world[worldpositionx][worldpositiony] = 2; worldpositionx = globalxy[0][1]; //redundant line, but for clarity

if(world[worldpositionx+1][worldpositiony] == 0)
{
    worldpositionx = worldpositionx +1;
    globalxy[0][1] = worldpositionx;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx-1][worldpositiony] = 0;
  
    //if position +1 is 0, drop. else end loop
}

}

void move(void)
{
//sideways movement
movement[0][0] = GetInt();
worldpositiony = globalxy[0][1];
worldpositionx = globalxy[1][0];
world[worldpositionx][worldpositiony] = 2;

if((movement[0][0] == 4) &amp;&amp; (world[worldpositionx][worldpositiony-1] == 0))  
{
    worldpositiony = worldpositiony -1; 
    globalxy[0][1] = worldpositiony;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx][worldpositiony+1] = 0;
}
else if((movement[0][0] == 6) &amp;&amp; (world[worldpositionx][worldpositiony+1] == 0))
{
    worldpositiony = worldpositiony +1; 
    globalxy[0][1] = worldpositiony;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx][worldpositiony-1] = 0;
}
else
{
    printf("An error occured \n");
}

//use a variable to track whether to move up down, or sideways. using get int. }

void instructions(void)
{
printf("Press 4 and 6 to move, and press 8 to jump, and press the 7 key to mega jump. Please input your move. \n");
}

/**

  • Clears screen using ANSI escape sequences.

void clear(void) { printf("\033[2J"); printf("\033[%d;%dH", 0, 0); } */

//global variable is not being treated as a global variable. I need to to change it another way. With correct replacement. //pointers seem to be one way to do this. point to the variable that the global variable pulls. and when I want to change it change the value of the things pointed to. //or else find an elegant way to track both of these with local variables. maybe merge movement and gravity so its on the same level.

//END of CODE

If there is better way to show this code, please let me know.

🌐
University of Texas
farside.ph.utexas.edu › teaching › 329 › lectures › node19.html
Global variables
When an argument is passed by reference ... which is called: hence, a change in one variable is automatically mirrored in the other. However, there is a third method of transferring information from one function to another. It is possible to define variables which are global in extent: ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › global-variables-in-c
Global Variables in C - GeeksforGeeks
A global variables are declared outside all functions, usually at the top of the program. Global variables have a program-wide scope which means can be accessed and modified by any function in the program.
Published   3 weeks ago
🌐
Hero Vired
herovired.com › learning-hub › topics › global-variable-in-c
Global Variable in C Programming: Examples, How to Declare
September 14, 2024 - Here, maxUsers is a constant global variable. It’s available to every function, but its value can’t be changed.
Find elsewhere
🌐
OnlineGDB
question.onlinegdb.com › 15049 › modify-global-variable-function-continue-value-functions
Can i modify a global variable in a function and continue with that same value in other functions? - OnlineGDB Q&A
The problem goes like this /* Objective: By the 3rd printf on the main function it needs to say 0 *\ ... (); } else { printf("Test failed"); } }
🌐
Scaler
scaler.com › home › topics › what is global variable in c?
What is Global Variable in C? - Scaler Topics
May 21, 2024 - Because the new value of pi was 4.14, the square() function squared 4.14 and we got 17.139603 as the new value of pi. Example 3: Redefining a global variable. ... From the above example, we can observe that C does not allow us to redefine the value of a global variable. When we tried to redefine the global variable, we got a redefinition of 'var' error. However, we could change the value of global variables in functions like we did in the previous example.
🌐
PrepBytes
prepbytes.com › home › c programming › global variable in c
Global Variable in C
January 8, 2024 - For example: #include int globalVar; // Declaration of a global variable · Q3: Can global variables be modified by any function in the program? A3: Yes, global variables can be modified by any function that has access to them. However, it is essential to be mindful of potential side effects and unintended changes, as global variables can introduce challenges related to code maintainability.
🌐
WsCube Tech
wscubetech.com › resources › c-programming › global-variables
Global Variables in C Programming (With Examples)
4 weeks ago - Learn in this tutorial about C global variables with examples. Understand their scope, usage, benefits, and limitations. Read now!
🌐
BYJUS
byjus.com › gate › global-variable-in-c
Use of the Global Variable in C
September 20, 2022 - You can notice that in line 4, x and y get declared as two of the global variables of the type int. Here, the variable x will get initialized automatically to 0. Then one can use variables like x and y inside any of the given functions. Also notice that inside the func_2() function, there exists a local variable that has the same name as the global variable.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 101634-controlling-modifying-global-variable.html
controlling modifying global variable
April 11, 2008 - Use a local variable instead, and only pass it by value to all other functions except that one function, where you pass its address instead of its value. Of course, it doesn't have to be a local variable, just as long as you pass it to code that doesn't have the right to access it directly, and either use pass by value or by const pointer (for larger pieces of data pass by pointer is more efficient, and const will ensure that your code doesn't accidentally write to the data). Of course, if you make it global, there's still the chance that some code will access the variable AS A GLOBAL, which can only be detected by code inspection [or randomly changing the name of the variable and the allowed changes and see what breaks!] -- Mats
🌐
freeCodeCamp
forum.freecodecamp.org › t › changing-a-global-variables-value-with-a-function-with-the-variable-passed-as-an-argument › 381692
Changing a global variable's value with a function with the variable passed as an argument - The freeCodeCamp Forum
April 30, 2020 - I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return …
🌐
Developerdocs
developerdocs.in › C › c_variables › global_variable
Understanding Global Variables in C: A Beginner's Guide – Nextra
The main() function and the display() function can both access and modify x. ... In this example, we will modify the global variable x inside one function and observe how the change affects other functions that use the same global variable.
🌐
Code Quoi
codequoi.com › en › local-global-static-variables-in-c
Local, Global and Static Variables in C - codequoi
Here, the foo function declares ... pointer). Then it can modify the value stored at that address. This is why when main later reads the value of this variable, it will have changed. When we declare a variable outside of any function, it is a global variable....