C Variables

1. What is a Variable?

  • A variable is a named memory location used to store data.

  • Each variable has:

    1. Name (Identifier) → The name you give it.

    2. Data Type → The type of data it can store (int, float, char, etc.).

    3. Value → The actual data stored.

Example:

int age = 25; // age is a variable of type int storing 25

2. Rules for Naming Variables

  1. Must start with a letter or underscore (_).

  2. Can contain letters, digits, and underscores.

  3. Cannot be a C keyword (like int, float, return).

  4. Case-sensitive (Ageage).

Valid Examples:

int age;
float _height;
char grade1;

Invalid Examples:

int 1age; // starts with digit ❌
float float; // keyword ❌

3. Variable Declaration and Initialization

(a) Declaration

  • Tells the compiler the type and name of a variable.

int age;
float height;
char grade;

(b) Initialization

  • Assigns a value at the time of declaration.

int age = 25;
float height = 5.9;
char grade = 'A';
  • You can also assign a value later:

int age;
age = 25;

4. Data Types of Variables

C has basic data types:

Data Type Memory Size Example
int 4 bytes int age = 25;
float 4 bytes float pi = 3.14;
double 8 bytes double d = 3.14159;
char 1 byte char grade = ‘A’;
  • int → Integer numbers

  • float → Decimal numbers

  • double → More precise decimal numbers

  • char → Single character


5. Multiple Variables Declaration

You can declare multiple variables of the same type in a single line:

int x = 10, y = 20, z = 30;
float a = 1.5, b = 2.5;

6. Constants vs Variables

  • Variables → Value can change.

  • Constants → Value cannot change. Use const keyword.

const float PI = 3.14159;
// PI = 3.14; // ❌ Not allowed

7. Example Program Using Variables


 

Output:

Age: 25
Height: 5.9
Grade: A

8. Tips

  1. Always choose meaningful names (age instead of a).

  2. Use consistent naming convention (like snake_case or camelCase).

  3. Remember C is case-sensitive.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *