Q:

Write a C program to How to define, modify and access a global variable

0

C program to define, modify and access a global variable

In this c program we are going to tell you how to declare, define, modify and access a global variable inside main and other functions?

A global function can be accessed and modified anywhere including main() and other user defined functions.

In this program we are declaring a global variable x which is an integer type, initially we are assigning the variable with the value 100.

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), this function will take an integer argument and assign the value into x.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C program - Define, Modify and Access a Global Variable

Let's consider the following example:

#include <stdio.h>

//declaration with initialization
int x=100;

//function to modify value of global variable
void modify_x(int val)
{
	x=val;
}
int main()
{
	printf("1) Value of x: %d\n",x);
	
	//modifying the value of x
	x=200;
	printf("2) Value of x: %d\n",x);
	
	//modifying value from function
	modify_x(300);
	printf("3) Value of x: %d\n",x);
	
	return 0;
}

Output

    1) Value of x: 100
    2) Value of x: 200
    3) Value of x: 300

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now