Docsity

C programming variable (Declaration, Initialization, and Scope), Lab Reports of C programming

Partial preview of the text

Download C programming variable (Declaration, Initialization, and Scope) and more Lab Reports C programming in PDF only on Docsity!

Variables in C

Declaration, Initialization, and Scope

A comprehensive guide to C programming fundamentals

What is a Variable? Definition

  • A named memory location that holds a value
  • Can store different data types (int, float, char,

etc.)

  • Value can be changed during program execution

int age = 25;

float salary = 50000.50;

char grade = 'A';

age = 26;

// Value changed

Variable Initialization Initialization is assigning an initial value to a variable at the time of declaration.

Declaration vs Initialization:

Declaration Only

int age;

Variable declared
Value unknown
(garbage value)

Declaration + Initialization

int age = 25;

Variable declared
Value assigned

Multiple Initialization Methods:

int x = 10, y = 20, z = 30;

Variable Scope Scope defines the region where a variable is accessible and valid.

1. Local Scope

void myFunc() { int x = 10; // Local } Valid only within the function block

2. Global Scope

int x = 5; // Global void myFunc() { // Can use x here } Accessible throughout entire program

3. Block Scope

for (int i = 0; i < 10; i++) { } // i exists only in loop | if (x > 5) { int y = 20; } // y exists only in block