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.

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

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.