Local Variable in C/C++

Declaring and Initializing Local Variable in C/C++

Before declaring local variable we must be know that:
1- The scope of local variables will be within the function only.
2- Variables should be declared in the C program before to use.

Declaring the variable

Declaring the variable means defoliation of variable, means that what is the name of your variable and how much memory space reserved for this variable.

Initializing variable

where Initializing means that assigning the value to variable. You can declare and initialize the variable at once.
Now we take an example


#include<stdio.h>
void test();
int main()
{
int marks = 345, t_marks = 500;
printf("\n Marks = %d  \n Total Marks = %d", marks, t_marks);
}

if you run this code this will return
Marks=345;
Total Marks=500
Note: \n us used to take control on next line.
Now take an other example with two function one is main and other is test function.


#include<stdio.h>
void test();
int main()
{
int marks = 345, t_marks = 500;
printf("\n Marks = %d  \n Total Marks = %d", marks, t_marks);
}

void test()
{
printf("\n Marks = %d  \n Total Marks = %d", marks, t_marks);
}

If we Run this code it will return Un declaration of marks and t_marks error because / marks and t_marks are local variables of main function and these variables are having scope within this main function only. These are not visible to test function. If you try to access these variable in test function, you will get 'marks' undeclared and 't_marks' undeclared error