๐Ÿ“ฆ Variables and Constants in C Language

Understanding Changeable and Fixed Data

๐Ÿ”น Variable in C

What 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;
Example:
int age;
float salary;
char grade;

Article Algo

๐Ÿ“Œ 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 Using const Keyword
  • Value cannot be modified after declaration
#include <stdio.h>
int main() {
  const int PI = 3.14;
  printf("%d", PI);
  return 0;
}
2๏ธโƒฃ Constant Using #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;
}
3๏ธโƒฃ Literal Constants

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;
}
Output:
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 const for safer programming