Problem 47

author
By Supreme2023-03-15
Problem Statement :
Write a C program using global variable, static variable
Code:

#include <stdio.h>

void func1();
void func2();
int global_var = 0;

int main() {
//47. Write a C program using global variable, static variable.


func1();
func1();
return 0;
}


void func1() {
static int static_var = 0;
global_var++;
static_var++;
printf("\nIn func1, global_var = %d, static_var = %d\n", global_var, static_var);
}

void func2() {
printf("\nIn func2, global_var = %d\n", global_var);
}

Description :
  • This program demonstrates the use of global and static variables in a C program.
  • The program includes the header file stdio.h, which provides input/output functions.
  • The program declares two functions func1 and func2, as well as a global variable global_var initialized to 0.
  • The main function is defined, which does the following: a. Calls the func1 function twice. b. Returns 0 to the operating system.
  • The func1 function is defined, which does the following: a. Defines a static variable static_var initialized to 0. Static variables retain their value between function calls. b. Increments the global variable global_var and static_var. c. Prints the current values of global_var and static_var to the console.
  • The func2 function is defined, which does the following: a. Prints the current value of the global variable global_var to the console.
  • When the program is run, the main function is called, which in turn calls func1 twice. func1 increments the value of the global variable global_var and the static variable static_var each time it is called, and prints the values to the console. Since static_var is a static variable, it retains its value between function calls.
  • The output of the program shows the values of global_var and static_var after each call to func1.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.