Online Courses
Free Tutorials  Go to Your University  Placement Preparation 

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence || Labeled as Highest Rated Course by Udemy

Apply Coupon

2.

Complete Machine Learning & Data Science with Python| ML A-Z Apply Coupon

3.

Complete Python Programming from scratch | Python Projects Apply Coupon
    More Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited by
 
Best answer

Static Variable in C

Static variables in a program preserve there value even if program goes out of scope unlike local and global variable. For example a static variable can be used to count how many times a function is called in a program.

Static variables can not be assigned variable values they can be assigned only constant values.

A static variable is declared using static keyword.

Syntax :

static data_type variable_name = value;

Static variables are assigned memory in data memory instead of stack segment.

Example :

#include<stdio.h>
#include<conio.h>

//fun() function containing static variable count
int fun()
{

//Declaration of static variable count
static int count=0;
count++;
return count;
}
void main()
{
clrscr();
printf("\nCall to fun() %d times",fun());
printf("\nCall to fun() %d times",fun());
printf("\nCall to fun() %d times",fun());
getch();
}

Output :

Global Variable

The variables declared outside any function are called global variables. They are not limited to any function. Any function can access and modify global variables. Global variables are automatically initialized to 0 at the time of declaration.

Global variables are generally declared after header files so that they can be used be every function in the program.

Example :

#include<stdio.h>
#include<conio.h>

//Declaration of global variable
int count;

//Declaration of recursion variable
long int recursion(int n);
void main()
{
int n;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, recursion(n));

//Printing value of global variable count
printf("\nRecursion function called %d time to calculate factorial",count);
getch();
}

long int recursion(int n)
{

//Increment in count
count++;
if (n>=1)
return n*recursion(n-1);
else
return 1;
}

Output :

Output of above program showing factorial of a number


For More GTU C Programming Lab Experiments Click Here

3.3k questions

7.1k answers

394 comments

4.6k users

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...