Variables in C can also be categorized based on their scope and lifetime:
Local Variables: Declared inside a function or block, accessible only within that function or block.
Global Variables: Declared outside of all functions and accessible from any part of the program.
Static Variables: Retain their value between function calls, even if declared within a function.
Automatic (auto) Variables: Default for local variables in C.
Register Variables: Stored in CPU registers for quick access (used for performance optimization).
c
Copy code
#include <stdio.h>
int main() {
int a = 10; // Local variable
printf("Value of a: %d\n", a);
return 0;
}
c
Copy code
#include <stdio.h>
void printNumber() {
int num = 42; // Local variable
printf("Number: %d\n", num);
}
int main() {
printNumber();
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int x = 5; // Local variable
x += 10; // Modify local variable
printf("Value of x: %d\n", x);
return 0;
}
c
Copy code
#include <stdio.h>
void testScope() {
int a = 100; // Local variable
printf("Inside function, a = %d\n", a);
}
int main() {
int a = 50; // Local variable
printf("Inside main, a = %d\n", a);
testScope();
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) { // Local variable inside the loop
printf("i = %d\n", i);
}
// printf("%d", i); // Error: i is not accessible outside the loop
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int a = 10;
printf("Outer block a: %d\n", a);
{
int a = 20; // Local variable in inner block
printf("Inner block a: %d\n", a);
}
printf("Outer block a again: %d\n", a);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int num = 15;
if (num > 10) {
int diff = num - 10; // Local variable inside if block
printf("Difference: %d\n", diff);
}
return 0;
}
c
Copy code
#include <stdio.h>
int addNumbers() {
int a = 5, b = 10; // Local variables
return a + b;
}
int main() {
int sum = addNumbers();
printf("Sum: %d\n", sum);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int x = 10, y = 20;
int temp = x; // Temporary local variable
x = y;
y = temp;
printf("After swapping, x = %d, y = %d\n", x, y);
return 0;
}
c
Copy code
#include <stdio.h>
void countdown(int n) {
if (n <= 0) {
printf("Blastoff!\n");
return;
}
int local = n; // Local variable in each recursion frame
printf("%d\n", local);
countdown(n - 1);
}
int main() {
countdown(5);
return 0;
}
Local Variables are declared inside functions, blocks, or scopes and are accessible only within those scopes.
Each example highlights different contexts in which local variables are used. Let me know if you'd like further clarification!
c
Copy code
#include <stdio.h>
int globalVar = 100; // Global variable
int main() {
printf("Global Variable: %d\n", globalVar);
return 0;
}
c
Copy code
#include <stdio.h>
int globalVar = 50; // Global variable
void printGlobal() {
printf("Global Variable in function: %d\n", globalVar);
}
int main() {
printf("Global Variable in main: %d\n", globalVar);
printGlobal();
return 0;
}
c
Copy code
#include <stdio.h>
int globalVar = 10; // Global variable
void modifyGlobal() {
globalVar += 20; // Modify global variable
}
int main() {
printf("Before modification: %d\n", globalVar);
modifyGlobal();
printf("After modification: %d\n", globalVar);
return 0;
}
c
Copy code
#include <stdio.h>
int globalCounter = 0; // Global variable
void incrementCounter() {
globalCounter++;
}
int main() {
for (int i = 0; i < 5; i++) {
incrementCounter();
}
printf("Global Counter: %d\n", globalCounter);
return 0;
}
c
Copy code
#include <stdio.h>
int configFlag = 1; // Global variable for configuration
void process() {
if (configFlag) {
printf("Configuration is enabled.\n");
} else {
printf("Configuration is disabled.\n");
}
}
int main() {
process();
configFlag = 0; // Change global variable
process();
return 0;
}
c
Copy code
#include <stdio.h>
int globalArray[5] = {1, 2, 3, 4, 5}; // Global array
void printArray() {
for (int i = 0; i < 5; i++) {
printf("%d ", globalArray[i]);
}
printf("\n");
}
int main() {
printf("Global Array: ");
printArray();
return 0;
}
c
Copy code
#include <stdio.h>
int callCount = 0; // Global variable
void incrementCallCount() {
callCount++;
}
int main() {
incrementCallCount();
incrementCallCount();
incrementCallCount();
printf("Function called %d times\n", callCount);
return 0;
}
c
Copy code
#include <stdio.h>
int sharedData = 42; // Global variable
void modifyData() {
sharedData *= 2;
}
void printData() {
printf("Shared Data: %d\n", sharedData);
}
int main() {
printData();
modifyData();
printData();
return 0;
}
c
Copy code
#include <stdio.h>
int totalSum = 0; // Global variable
void calculateSum(int n) {
if (n <= 0) return;
totalSum += n;
calculateSum(n - 1);
}
int main() {
calculateSum(5);
printf("Total Sum: %d\n", totalSum);
return 0;
}
c
Copy code
#include <stdio.h>
int isRunning = 0; // Global variable
void startProcess() {
isRunning = 1;
printf("Process started.\n");
}
void stopProcess() {
isRunning = 0;
printf("Process stopped.\n");
}
int main() {
startProcess();
if (isRunning) {
printf("Process is currently running.\n");
}
stopProcess();
if (!isRunning) {
printf("Process is currently stopped.\n");
}
return 0;
}
Global Variables are declared outside of all functions and accessible throughout the program.
They are ideal for data that needs to be shared between multiple functions or tracked globally, like configurations, counters, or shared arrays.
Use global variables cautiously, as excessive usage can lead to side effects and maintenance challenges.
c
Copy code
#include <stdio.h>
void increment() {
static int count = 0; // Static variable retains its value
count++;
printf("Count: %d\n", count);
}
int main() {
increment();
increment();
increment();
return 0;
}
c
Copy code
#include <stdio.h>
void display() {
static int num = 5; // Static variable
printf("Static Number: %d\n", num);
num++;
}
int main() {
for (int i = 0; i < 3; i++) {
display();
}
return 0;
}
c
Copy code
#include <stdio.h>
void countCalls() {
static int callCount = 0; // Static variable
callCount++;
printf("Function called %d times\n", callCount);
}
int main() {
countCalls();
countCalls();
countCalls();
return 0;
}
c
Copy code
#include <stdio.h>
void func1() {
static int x = 10; // Static variable
printf("Value in func1: %d\n", x);
x++;
}
void func2() {
func1(); // func2 relies on func1's static variable
}
int main() {
func1();
func2();
return 0;
}
c
Copy code
#include <stdio.h>
void accumulate(int value) {
static int sum = 0; // Static variable retains accumulated value
sum += value;
printf("Accumulated Sum: %d\n", sum);
}
int main() {
accumulate(10);
accumulate(20);
accumulate(30);
return 0;
}
c
Copy code
#include <stdio.h>
void toggleStatus() {
static int isOn = 0; // Static variable for status
isOn = !isOn;
printf("Status: %s\n", isOn ? "ON" : "OFF");
}
int main() {
toggleStatus();
toggleStatus();
toggleStatus();
return 0;
}
c
Copy code
#include <stdio.h>
void recursiveFunction(int n) {
static int depth = 0; // Static variable for recursion depth
depth++;
printf("Recursion Depth: %d, n = %d\n", depth, n);
if (n > 0) {
recursiveFunction(n - 1);
}
depth--;
}
int main() {
recursiveFunction(3);
return 0;
}
c
Copy code
#include <stdio.h>
void objectCounter() {
static int objectCount = 0; // Static variable for counting
objectCount++;
printf("Object Count: %d\n", objectCount);
}
int main() {
objectCounter();
objectCounter();
objectCounter();
return 0;
}
c
Copy code
#include <stdio.h>
void setConfig(int configValue) {
static int config = 0; // Static variable to store configuration
if (configValue != -1) {
config = configValue;
}
printf("Current Configuration: %d\n", config);
}
int main() {
setConfig(5);
setConfig(-1); // Retrieve existing config
setConfig(10);
return 0;
}
c
Copy code
#include <stdio.h>
static int globalStatic = 100; // Static variable in file scope
void showValue() {
printf("Global Static Variable: %d\n", globalStatic);
}
int main() {
showValue();
globalStatic += 50;
showValue();
return 0;
}
Static Variables:
Retain their value between function calls.
Are initialized only once (default initialization is 0 if not explicitly set).
Scope:
Can be local to a function or global (restricted to the file).
Useful for maintaining state across function calls or limiting variable visibility.
Applications:
Count function calls, track status, accumulate values, maintain recursion depth, etc.
Note that automatic variables are the default storage class for local variables, so explicitly using the auto keyword is optional.
c
Copy code
#include <stdio.h>
int main() {
auto int x = 10; // Local auto variable
printf("Value of x: %d\n", x);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int y = 20; // Local variables are auto by default
printf("Value of y: %d\n", y);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
auto int loopVar = i * 2; // Auto variable in the loop
printf("Loop Variable: %d\n", loopVar);
}
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
auto int x = 5; // Outer scope auto variable
printf("Outer x: %d\n", x);
{
auto int x = 10; // Inner scope auto variable
printf("Inner x: %d\n", x);
}
printf("Outer x again: %d\n", x);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
auto int a = 10, b = 20; // Multiple auto variables
int sum = a + b;
printf("Sum of a and b: %d\n", sum);
return 0;
}
c
Copy code
#include <stdio.h>
void displayAutoVar() {
auto int localVar = 42; // Auto variable inside a function
printf("Local Variable: %d\n", localVar);
}
int main() {
displayAutoVar();
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
int number = 7;
if (number > 5) {
auto int result = number * 2; // Auto variable in if block
printf("Result: %d\n", result);
}
return 0;
}
c
Copy code
#include <stdio.h>
void showLifetime() {
auto int temp = 10; // Created and destroyed during each call
printf("Temp value: %d\n", temp);
temp++;
}
int main() {
showLifetime();
showLifetime();
return 0;
}
c
Copy code
#include <stdio.h>
void countdown(int n) {
if (n <= 0) {
printf("Blastoff!\n");
return;
}
auto int current = n; // Auto variable for current level
printf("Current: %d\n", current);
countdown(n - 1);
}
int main() {
countdown(5);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
auto int uninitializedVar; // Auto variable without initialization
printf("Uninitialized Variable: %d (garbage value)\n", uninitializedVar);
return 0;
}
Automatic (Auto) Variables:
Automatically created when entering the block/scope and destroyed on exit.
Default storage class for local variables.
Explicit use of the auto keyword is rare in modern C.
Scope and Lifetime:
Visible only within their defining block or function.
Lifetime ends when the scope exits.
Examples:
These programs showcase auto variables in loops, functions, nested scopes, and recursive functions.
register is a storage class specifier that suggests to the compiler that the variable should be stored in a register for faster access.
c
Copy code
#include <stdio.h>
int main() {
register int a = 10; // Register variable
printf("Value of a: %d\n", a);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int i; // Register variable
for (i = 0; i < 5; i++) {
printf("i = %d\n", i);
}
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int sum = 0, i;
for (i = 1; i <= 5; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
return 0;
}
c
Copy code
#include <stdio.h>
void display() {
register int x = 100; // Register variable inside function
printf("Value of x: %d\n", x);
}
int main() {
display();
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int a = 5, b = 10, result;
result = a * b;
printf("Multiplication result: %d\n", result);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int i;
int arr[] = {1, 2, 3, 4, 5};
for (i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
c
Copy code
#include <stdio.h>
void factorial(register int n) {
if (n <= 1) return;
printf("Factorial step: %d\n", n);
factorial(n - 1);
}
int main() {
factorial(5);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int i, idx = 3;
int arr[] = {10, 20, 30, 40, 50};
printf("Element at index %d: %d\n", idx, arr[idx]);
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register int num = 15; // Register variable
if (num > 10) {
printf("The number is greater than 10\n");
} else {
printf("The number is 10 or less\n");
}
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
register long i, sum = 0;
for (i = 0; i < 1000000; i++) {
sum += i;
}
printf("Sum of first 1000000 numbers: %ld\n", sum);
return 0;
}
Register Variables:
register is used to suggest to the compiler that the variable should be stored in a processor register instead of RAM to optimize access speed.
They are typically used for variables that are heavily accessed in tight loops or performance-critical code.
Limitation: You cannot take the address of a register variable using the address-of operator (&), as registers don't have memory addresses in the usual sense.
Use Cases:
Loop Optimization: Register variables are used in loops and iterative processes where performance can be crucial.
Function Performance: Especially when functions involve variables that are frequently accessed or modified.