c
examples
examples.c🔧c
/*
* ============================================================================
* VARIABLES AND CONSTANTS IN C - EXAMPLES
* ============================================================================
* This file demonstrates variable declaration, initialization, scope,
* lifetime, and different types of constants.
*
* Compile: gcc -Wall examples.c -o examples
* Run: ./examples
* ============================================================================
*/
#include <stdio.h>
// Global variable - accessible throughout the program
int globalCounter = 0;
// Global constant using const
const float PI = 3.14159265f;
// Symbolic constants using #define
#define MAX_SIZE 100
#define GREETING "Hello, World!"
#define SQUARE(x) ((x) * (x))
/*
* Example 1: Variable Declaration and Initialization
* ---------------------------------------------------
* Shows different ways to declare and initialize variables.
*/
void example_declaration_initialization() {
printf("\n=== Example 1: Declaration and Initialization ===\n");
// Method 1: Declaration then assignment
int a;
a = 10;
printf("Method 1 (separate): a = %d\n", a);
// Method 2: Declaration with initialization (preferred)
int b = 20;
printf("Method 2 (combined): b = %d\n", b);
// Method 3: Multiple declarations
int x = 1, y = 2, z = 3;
printf("Method 3 (multiple): x=%d, y=%d, z=%d\n", x, y, z);
// Different types
float price = 19.99f;
double precise = 3.14159265358979;
char grade = 'A';
printf("\nDifferent types:\n");
printf("float price: %.2f\n", price);
printf("double precise: %.14f\n", precise);
printf("char grade: %c\n", grade);
}
/*
* Example 2: Valid and Invalid Variable Names
* -------------------------------------------
* Demonstrates naming rules and conventions.
*/
void example_naming() {
printf("\n=== Example 2: Variable Naming ===\n");
// Valid names
int age;
int _count;
int student1;
int numberOfStudents;
int number_of_students;
int MAX_VALUE;
// Assign values
age = 25;
_count = 100;
student1 = 42;
numberOfStudents = 30;
number_of_students = 30;
MAX_VALUE = 1000;
printf("Valid variable names:\n");
printf("age = %d\n", age);
printf("_count = %d\n", _count);
printf("student1 = %d\n", student1);
printf("numberOfStudents = %d (camelCase)\n", numberOfStudents);
printf("number_of_students = %d (snake_case)\n", number_of_students);
printf("MAX_VALUE = %d (UPPER_CASE for constants)\n", MAX_VALUE);
// Invalid names (would cause compile errors):
// int 2nd; // Can't start with digit
// int my-var; // Can't use hyphen
// int my var; // Can't have space
// int int; // Can't use reserved word
// int #value; // Can't use special characters
printf("\nInvalid examples (commented out):\n");
printf("2nd - starts with digit\n");
printf("my-var - contains hyphen\n");
printf("my var - contains space\n");
printf("int - reserved keyword\n");
}
/*
* Example 3: Constants with const
* -------------------------------
* Using const keyword for constant values.
*/
void example_const() {
printf("\n=== Example 3: const Keyword ===\n");
const int MAX_STUDENTS = 100;
const float TAX_RATE = 0.08f;
const char NEWLINE = '\n';
const char MESSAGE[] = "This is constant";
printf("MAX_STUDENTS: %d\n", MAX_STUDENTS);
printf("TAX_RATE: %.2f\n", TAX_RATE);
printf("NEWLINE: (ASCII %d)%c", NEWLINE, NEWLINE);
printf("MESSAGE: %s\n", MESSAGE);
// Attempting to modify would cause error:
// MAX_STUDENTS = 200; // ERROR!
// Using const in calculations
int numStudents = 50;
float price = 100.0f;
float priceWithTax = price * (1 + TAX_RATE);
printf("\nUsing constants:\n");
printf("Students: %d / %d\n", numStudents, MAX_STUDENTS);
printf("Price: $%.2f, With Tax: $%.2f\n", price, priceWithTax);
}
/*
* Example 4: #define Preprocessor Constants
* -----------------------------------------
* Using #define for symbolic constants and macros.
*/
void example_define() {
printf("\n=== Example 4: #define Constants ===\n");
// Using defined constants
printf("MAX_SIZE: %d\n", MAX_SIZE);
printf("GREETING: %s\n", GREETING);
printf("SQUARE(5): %d\n", SQUARE(5));
printf("SQUARE(3+2): %d\n", SQUARE(3+2)); // ((3+2)*(3+2)) = 25
// Array with defined size
int numbers[MAX_SIZE];
numbers[0] = 1;
numbers[MAX_SIZE - 1] = 100;
printf("\nArray with MAX_SIZE:\n");
printf("First element: %d\n", numbers[0]);
printf("Last element: %d\n", numbers[MAX_SIZE - 1]);
// Conditional compilation
#define DEBUG 1
#if DEBUG
printf("\nDebug mode is ON\n");
#endif
#undef DEBUG // Undefine to turn off
}
/*
* Example 5: Enumeration Constants
* --------------------------------
* Using enum for related named constants.
*/
void example_enum() {
printf("\n=== Example 5: enum Constants ===\n");
// Basic enum (starts from 0)
enum Color { RED, GREEN, BLUE, YELLOW };
enum Color myColor = GREEN;
printf("Color values: RED=%d, GREEN=%d, BLUE=%d, YELLOW=%d\n",
RED, GREEN, BLUE, YELLOW);
printf("myColor = %d (GREEN)\n", myColor);
// Enum with explicit values
enum Weekday {
MONDAY = 1,
TUESDAY, // 2
WEDNESDAY, // 3
THURSDAY, // 4
FRIDAY, // 5
SATURDAY, // 6
SUNDAY // 7
};
enum Weekday today = FRIDAY;
printf("\nWeekday values:\n");
printf("MONDAY=%d, FRIDAY=%d, SUNDAY=%d\n", MONDAY, FRIDAY, SUNDAY);
printf("today = %d (FRIDAY)\n", today);
// Enum with gaps
enum StatusCode {
OK = 200,
NOT_FOUND = 404,
SERVER_ERROR = 500
};
enum StatusCode status = OK;
printf("\nHTTP Status: %d\n", status);
// Using enum in switch
printf("\nUsing enum in switch:\n");
switch (myColor) {
case RED: printf("Color is RED\n"); break;
case GREEN: printf("Color is GREEN\n"); break;
case BLUE: printf("Color is BLUE\n"); break;
case YELLOW: printf("Color is YELLOW\n"); break;
}
}
/*
* Example 6: Variable Scope
* -------------------------
* Demonstrates local, global, and block scope.
*/
// Global variable (already defined at top)
// int globalCounter = 0;
void incrementGlobal() {
globalCounter++; // Accessing global variable
int localVar = 100; // Local to this function
printf("In incrementGlobal: globalCounter=%d, localVar=%d\n",
globalCounter, localVar);
}
void example_scope() {
printf("\n=== Example 6: Variable Scope ===\n");
// Local variable
int localVar = 50;
printf("Initial globalCounter: %d\n", globalCounter);
printf("Local localVar: %d\n", localVar);
// Call function that modifies global
incrementGlobal();
incrementGlobal();
printf("After increments, globalCounter: %d\n", globalCounter);
// Block scope
printf("\nBlock scope demonstration:\n");
int outer = 10;
printf("Outer: %d\n", outer);
{
int inner = 20;
printf("Inside block - outer: %d, inner: %d\n", outer, inner);
// Can access and modify outer
outer = 15;
printf("Modified outer from block: %d\n", outer);
}
// inner is not accessible here
// printf("%d\n", inner); // ERROR!
printf("After block - outer: %d\n", outer);
}
/*
* Example 7: Variable Shadowing
* -----------------------------
* When inner scope variable hides outer scope variable.
*/
int shadowVar = 100; // Global
void example_shadowing() {
printf("\n=== Example 7: Variable Shadowing ===\n");
printf("Global shadowVar: %d\n", shadowVar);
int shadowVar = 200; // Local shadows global
printf("Local shadowVar: %d (shadows global)\n", shadowVar);
{
int shadowVar = 300; // Block shadows local
printf("Block shadowVar: %d (shadows local)\n", shadowVar);
}
printf("After block, shadowVar: %d (local)\n", shadowVar);
// Note: Can still access global using workaround (not recommended)
// extern int shadowVar; // Would refer to global
}
/*
* Example 8: Static Variables
* ---------------------------
* Variables that persist across function calls.
*/
void countCalls() {
static int callCount = 0; // Initialized only once
int normalVar = 0; // Reset each call
callCount++;
normalVar++;
printf("Call #%d: static=%d, normal=%d\n",
callCount, callCount, normalVar);
}
void example_static() {
printf("\n=== Example 8: Static Variables ===\n");
printf("Calling countCalls() multiple times:\n");
countCalls(); // static=1, normal=1
countCalls(); // static=2, normal=1
countCalls(); // static=3, normal=1
countCalls(); // static=4, normal=1
countCalls(); // static=5, normal=1
printf("\nStatic persists, normal resets each call.\n");
}
/*
* Example 9: Register Variables (Hint)
* ------------------------------------
* Suggesting storage in CPU registers for speed.
*/
void example_register() {
printf("\n=== Example 9: Register Variables ===\n");
register int i; // Hint: use register for speed
register int sum = 0;
// Fast loop with register variable
for (i = 1; i <= 1000000; i++) {
sum += i % 100; // Just some calculation
}
printf("Sum calculation complete: %d\n", sum);
// Note: Modern compilers optimize automatically
// The 'register' keyword is mostly ignored today
// Can't take address of register variable:
// int *ptr = &i; // ERROR!
printf("Note: 'register' is a hint, compiler may ignore it.\n");
}
/*
* Example 10: Different Initialization Methods
* --------------------------------------------
* Various ways to initialize variables.
*/
void example_initialization_methods() {
printf("\n=== Example 10: Initialization Methods ===\n");
// Basic types
int a = 10;
float b = 3.14f;
char c = 'X';
printf("Basic: a=%d, b=%.2f, c=%c\n", a, b, c);
// Arrays
int arr1[5] = {1, 2, 3, 4, 5}; // Full initialization
int arr2[5] = {1, 2}; // Partial (rest are 0)
int arr3[] = {1, 2, 3}; // Size inferred
int arr4[5] = {0}; // All zeros
printf("\nArrays:\n");
printf("arr1: ");
for (int i = 0; i < 5; i++) printf("%d ", arr1[i]);
printf("\narr2: ");
for (int i = 0; i < 5; i++) printf("%d ", arr2[i]);
printf("\narr3: ");
for (int i = 0; i < 3; i++) printf("%d ", arr3[i]);
printf("\narr4: ");
for (int i = 0; i < 5; i++) printf("%d ", arr4[i]);
printf("\n");
// Structures
struct Point {
int x;
int y;
};
struct Point p1 = {10, 20}; // Positional
struct Point p2 = {.x = 30, .y = 40}; // Designated (C99)
struct Point p3 = {.y = 60, .x = 50}; // Order doesn't matter
printf("\nStructures:\n");
printf("p1: (%d, %d)\n", p1.x, p1.y);
printf("p2: (%d, %d)\n", p2.x, p2.y);
printf("p3: (%d, %d)\n", p3.x, p3.y);
// String initialization
char str1[] = "Hello"; // Array
char str2[10] = "Hi"; // Larger array
char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicit
printf("\nStrings:\n");
printf("str1: \"%s\" (size: %zu)\n", str1, sizeof(str1));
printf("str2: \"%s\" (size: %zu)\n", str2, sizeof(str2));
printf("str3: \"%s\" (size: %zu)\n", str3, sizeof(str3));
}
/*
* Main Function
*/
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ VARIABLES AND CONSTANTS - EXAMPLES ║\n");
printf("║ Understanding C variables and constants ║\n");
printf("╚════════════════════════════════════════════════╝\n");
example_declaration_initialization();
example_naming();
example_const();
example_define();
example_enum();
example_scope();
example_shadowing();
example_static();
example_register();
example_initialization_methods();
printf("\n=== All Examples Completed! ===\n");
printf("Global PI constant used throughout: %.5f\n", PI);
printf("Final globalCounter value: %d\n", globalCounter);
return 0;
}