Variables in C: Definition, Rules, Examples & Types
In C programming, a variable is simply a name given to a memory location where data is stored. You can think of it like a box where you keep some value (number, character, etc.) and give that box a label (name).
Example: If we say int age = 18;, here:
- int → data type (integer)
- age → variable name
- 18 → value stored in that variable
Variable Declaration
datatype variable_name; // or for multiple variables: datatype variable1, variable2, variable3;
Examples:
int marks;→ a variable for storing marksfloat salary, bonus;→ two variables of type float
Rules for Naming Variables
There are some simple rules you must follow while naming variables in C:
- Variable names can have 1 to 255 characters (recommended: 1–31 characters).
- They must start with a letter or underscore (_).
- After the first letter, you can use letters and numbers (no spaces or special characters).
- Case-sensitive →
Ageandageare different. - You cannot use keywords (like
int,while,if) as variable names. - Use meaningful names: e.g.,
totalMarksis better thanx.
Valid vs Invalid Variable Names
| Valid | Invalid |
|---|---|
| studentMarks | 3students |
| grade_on_test | grade#1 |
| _value | total marks (space not allowed) |
Types of Variables in C
There are mainly 5 types of variables in C:
- Local Variable: Declared inside a function or block. Only accessible there.
Example: A variable insidemain(). - Global Variable: Declared outside all functions. Accessible throughout the program.
Example: A variable declared beforemain(). - Static Variable: Retains its value even after the function ends (declared using
statickeyword). - External Variable: Declared with
externkeyword. Can be shared across multiple files. - Automatic Variable: By default, variables inside a function are automatic. Declared using
auto(rarely used explicitly).
Comparison of Variables
| Type | Scope | Lifetime |
|---|---|---|
| Local | Inside function/block | Till function ends |
| Global | Whole program | Till program ends |
| Static | Inside function | Till program ends (retains value) |
Tips for Writing Good Variable Names
- Always use meaningful names (e.g.,
totalMarksinstead ofa). - Follow one style (camelCase or underscore_style).
- Do not use very long names.
- Avoid using confusing names like
O(letter O) orl(small L).
Conclusion
Variables are the foundation of any program. If you master how to declare, name, and use them correctly, you will write cleaner and more efficient C programs.