variable in c
- what is variable in c ?
- how to declare and initialize a variable ?
- declaration of variable
- initialization of variable
- local and global variable in c.
- local variable
- global variable
- question and answer.
variable in c
In c language a variable is a name assign to the memory location which holds a value. in c variables allows you to store the data, modify the data, and retrieve data in your program.
example :
int a;float b;
char ch;
How to declare and initialize a variable ?
Declaration of variable :
Syntax for declaring variable :
datatype variable_name;
- datatype: It specifies which type of data the variable will hold, such as int, float, char, etc.
- variable_name: it is the name you give to the variable.
#include <stdio.h>
int main ()
{
int num; //declaring variable name with type
return 0;
}
In above program we declared a vriable named num with int datatype which means the variable num will hold the integer value.
Initialization of variable :
#include <stdio.h>int main(){int n = 160;return 0;}
In the above example we declared variable named n with integer data type and assigned the value 160 to the variable.
local and global variable in c
Local variable : In c local variables are declared inside the function or a block of code and you can only accessed local variable inside that function or block. Local variables cannot be accessed from outside the function or block in which they are declared. Local variable is typically used for temporary storage within a specific function or block.
example
#include <stdio.h>int main(){int x; //declared local variable named xx=120;printf("value of x is %d",x);return 0;}
In the above example we declared a local variable names x within main function ,that mean it can only be used within the main function and not outside of it.
Global variable: Global variables are declared outside of any function and it can be accessed from any function in the program. In c global variables are quite different from local variables, Global variables have longer lifetime compared to local variables. Global variables are typically used for values that need to be shared among other functions.
example
#include <stdio.h>int x = 10; // declared a global variable named xin main(){printf("global variable is: %d",x);return 0;}
Questions
- What is a variable in C?
- How do you declare a variable in C?
- How do you initialize a variable in C?
- What is the syntax for declaring a variable in C?
- What is a local variable in C?
- What is a global variable in C?
- Where are local variables declared in C?
- Where are global variables declared in C?
- Can a local variable be accessed outside its function or block?
- Can a global variable be accessed from any function in a program?