Home » C Programming » Variables in C: Definition, Rules, and Types (With Examples)

Variables in C: Definition, Rules, and Types (With Examples)

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 marks
  • float 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-sensitiveAge and age are different.
  • You cannot use keywords (like int, while, if) as variable names.
  • Use meaningful names: e.g., totalMarks is better than x.

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:

  1. Local Variable: Declared inside a function or block. Only accessible there.
    Example: A variable inside main().
  2. Global Variable: Declared outside all functions. Accessible throughout the program.
    Example: A variable declared before main().
  3. Static Variable: Retains its value even after the function ends (declared using static keyword).
  4. External Variable: Declared with extern keyword. Can be shared across multiple files.
  5. 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., totalMarks instead of a).
  • Follow one style (camelCase or underscore_style).
  • Do not use very long names.
  • Avoid using confusing names like O (letter O) or l (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.


Leave a comment

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