๐ฆ Variables and Constants in C Language
Understanding Changeable and Fixed Data
๐น Variable in CWhat is a Variable?
A variable is a named memory location used to store data whose value can be changed during program execution.
Syntax:
data_type variable_name;
int age;
float salary;
char grade;
๐ Types of Variables in C (Based on Scope)
1๏ธโฃ Local Variable
- Declared inside a function or block
- Accessible only within that block
#include <stdio.h>
int main() {
int x = 10; // local variable
printf("%d", x);
return 0;
}
2๏ธโฃ Global Variable
- Declared outside all functions
- Accessible throughout the program
#include <stdio.h>
int global = 20;
int main() {
printf("%d", global);
return 0;
}
๐ Constant in C
What is a Constant?
A constant is a fixed value whose value cannot be changed during program execution.
๐ Types of Constants in C
1๏ธโฃ Constant Usingconst Keyword
- Value cannot be modified after declaration
#include <stdio.h>
int main() {
const int PI = 3.14;
printf("%d", PI);
return 0;
}
#define (Preprocessor)
- Does not use memory
- Value is replaced at compile time
#include <stdio.h>
#define PI 3.14
int main() {
printf("%.2f", PI);
return 0;
}
Fixed values written directly in the code.
10 // Integer constant
5.5 // Floating constant
'A' // Character constant
"Hello" // String constant
โ๏ธ Difference Between Variable and Constant
| Variable | Constant |
|---|---|
| Value can change | Value cannot change |
| Needs memory | May or may not need memory |
| Declared normally | Declared using const or #define |
| Used in calculations | Used as fixed values |
๐งช Example Program Using Variables and Constants
#include <stdio.h>
#define PI 3.14
int main() {
int radius = 5;
float area;
area = PI * radius * radius;
printf("Area of circle: %.2f", area);
return 0;
}
Area of circle: 78.50
๐ FAQs on Variables and Constants in C
Q1. What is a variable?
A variable is a memory location that stores data which can be changed during program execution.
Q2. What is a constant?
A constant is a fixed value that cannot be changed once defined.
Q3. What is the difference between const and #define?
const uses memory and follows data type rules, while #define is a preprocessor directive and does not use memory.
Q4. Can we change the value of a constant?
No, changing a constant value will cause a compilation error.
Q5. Can a variable be initialized at declaration?
Yes. Example: int x = 10;
๐ Key Points to Remember
- Variables store changeable data
- Constants store fixed values
- Use meaningful variable names
- Prefer
constfor safer programming