C Variables: Declaration, Initialization, Scope, and Examples
A variable in C is a named object used to store a value of a specified data type. Its type determines how the stored data is interpreted, which operations are permitted, and how much storage the implementation provides for it.
For example, an int variable stores an integer, a char variable stores a character-sized integer value, and a double variable stores a floating-point value. A variable’s value can usually change while the program runs unless its type is qualified with const.
Why C Programs Use Variables
Variables let a C program retain input, intermediate calculations, state, and final results. Meaningful variable names also make the relationship between data and operations easier to understand.
- Store values entered by a user or read from a file.
- Keep counters, totals, measurements, and status values.
- Pass data to functions and receive function results.
- Give descriptive names to values used in calculations.
C Variable Declaration Syntax
A basic variable declaration places a data type before an identifier:
int a;
In this statement, int is the type and a is the variable name. When this declaration appears at block or file scope without extern, it is also a definition because it causes storage to be reserved for the object.
The general form is:
type variable_name;
type variable_name = initial_value;
Rules for Naming Variables in C
A C variable name is an identifier. It must follow these rules:
- Use a letter or underscore as the first character:
counterand_indexare valid forms. - Use only letters, digits, and underscores:
student_countandvalue2are valid, butstudent-countis not. - Observe case: C is case-sensitive, so
total,Total, andTOTALare different identifiers. - Do not use a C keyword: Names such as
int,return, andwhileare reserved by the language. - Avoid reserved identifier patterns: In particular, identifiers beginning with an underscore followed by an uppercase letter, and identifiers containing two leading underscores, are reserved for the implementation.
Prefer names that describe the stored value, such as item_count, average_score, or is_valid. Very short names can still be suitable for small loop counters or mathematical expressions where their meaning is clear.
C Variable Declaration, Definition, and Initialization
The terms declaration, definition, initialization, and assignment describe related but distinct operations.
| Term | Meaning in C | Example |
|---|---|---|
| Declaration | Introduces an identifier and its type to the compiler. | extern int total; |
| Definition | Declares an object and provides its storage. | int total; |
| Initialization | Supplies the value an object receives when it is defined. | int total = 10; |
| Assignment | Stores a new value in an object after its definition. | total = 20; |
Every definition is a declaration, but a declaration using extern without an initializer does not normally define the object. It states that the definition exists elsewhere.
Initializing C Variables with Integer, Floating-Point, and Character Values
int age = 25; // 'age' is defined as an integer and initialized to 25
float salary = 45000.50; // 'salary' is defined as a float and initialized to 45000.50
char grade = 'A'; // 'grade' is defined as a char and initialized to 'A'
ageis anintinitialized to25.salaryis afloat. The unsuffixed literal45000.50has typedoubleand is converted tofloatduring initialization.gradeis acharinitialized with the character constant'A'.
A floating-point literal can use an f suffix when a float value is intended, as in 45000.50f.
Declaring Multiple C Variables in One Statement
int x = 10, y = 20, z = 30; // Multiple integer variables defined and initialized
This statement defines three int variables and initializes them to 10, 20, and 30. Although C permits several declarators in one statement, separate declarations can be clearer when the variables have different purposes or complex pointer types.
Common Data Types Used for C Variables
| Type | Typical purpose | Example |
|---|---|---|
char | Character-sized integer data | char grade = 'A'; |
int | Whole numbers | int count = 12; |
unsigned int | Nonnegative integer values within its range | unsigned int items = 12U; |
float | Single-precision floating-point values | float rate = 2.5f; |
double | Double-precision floating-point values | double distance = 12.75; |
_Bool | Boolean value represented as zero or one | _Bool ready = 1; |
The C standard defines minimum requirements and relationships for these types, but their exact sizes can vary by implementation. Use sizeof when the size in the current implementation matters. For integers with specified widths when those types are available, include <stdint.h> and use names such as int32_t.
Local and Global Variables in C
Calling a variable local or global describes where it is declared and where its name can be used. Environment variables maintained by an operating system are not a separate category of C language variable; a C program accesses them through library or platform facilities.
Local C Variables
A variable declared inside a function or compound statement has block scope. Its name can be used from its declaration to the end of the enclosing block, subject to any nested declaration that hides it.
Global C Variables
A variable defined outside every function has file scope. Its name is visible from its declaration to the end of that source file. Whether another source file can refer to the same object depends on linkage and declarations such as extern.
C Example Using Global and Local Variables
#include <stdio.h>
/* Global variable declaration */
int globalVar = 100;
int main() {
/* Local variable declaration */
int localVar = 50;
/* Declaration and initialization in one line */
int sum = globalVar + localVar;
printf("Global Variable: %d\n", globalVar);
printf("Local Variable: %d\n", localVar);
printf("Sum: %d\n", sum);
return 0;
}
globalVar has file scope and static storage duration. The variables localVar and sum have block scope and, because they are ordinary local variables, automatic storage duration.
The program produces:
Global Variable: 100
Local Variable: 50
Sum: 150
Scope, Storage Duration, and Linkage of C Variables
Scope, storage duration, and linkage answer different questions about a C variable:
- Scope: The region of source code in which an identifier is visible.
- Storage duration: The period during program execution for which the object exists.
- Linkage: Whether declarations in the same or different scopes refer to the same identifier or object.
| Variable form | Usual scope | Storage duration |
|---|---|---|
| Ordinary variable inside a block | Block | Automatic |
static variable inside a block | Block | Static |
| Variable defined outside functions | File | Static |
| Dynamically allocated object | Accessed through a pointer | Allocated |
A block-scope variable declared with static keeps its stored value between function calls, but its name remains visible only within its block.
Initial Values and Uninitialized C Variables
An object with static storage duration is initialized before program execution. If no explicit initializer is provided, arithmetic types are initialized to zero and pointers are initialized to null pointers.
An ordinary automatic variable declared without an initializer has an indeterminate value. Reading that value before storing a valid value can produce undefined behavior in common cases. Initialize local variables before their first use unless every possible control-flow path assigns them first.
int count = 0;
double total = 0.0;
char status = 'N';
Constants and Read-Only Variables with const
The const qualifier indicates that a program must not modify an object through that qualified type.
const double tax_rate = 0.18;
const int maximum_attempts = 3;
A const-qualified object is still an object with a type, scope, and storage duration. It is different from a preprocessor macro created with #define.
Common C Variable Errors
- Using an uninitialized local variable: Assign a valid value before reading it.
- Assigning an incompatible value: Check conversions, ranges, signs, and possible loss of precision.
- Using the wrong
printfformat: Match each conversion specification to the argument type required byprintf. - Confusing assignment and comparison:
=assigns a value, while==compares values. - Hiding a variable: A declaration in an inner block can hide an identifier with the same name in an outer scope.
- Assuming fixed type sizes: Use
sizeof, implementation documentation, or suitable types from<stdint.h>. - Overusing global variables: Unrestricted shared state can make data flow and side effects difficult to track.
C Variable QA Checklist
- Verify that each variable has a type suitable for its values and operations.
- Confirm that every automatic variable is initialized before it is read.
- Check that variable names follow C identifier and reserved-name rules.
- Review integer conversions for overflow, sign changes, and truncation.
- Match
printfandscanfconversion specifications to the required argument types. - Confirm that each variable has the narrowest practical scope.
- Check whether a global definition should instead use
staticfor internal linkage or anexterndeclaration in another file. - Compile with warnings enabled and investigate every relevant diagnostic.
C Variables: Key Points
- A C variable is a named object with a specific type.
- A definition reserves storage, while an
externdeclaration can refer to a definition elsewhere. - Initialization occurs when an object is defined; assignment changes its value later.
- Scope controls identifier visibility, while storage duration controls how long the object exists.
- Automatic local variables should be initialized before they are read.
- Exact data-type sizes and ranges can depend on the C implementation.
Frequently Asked Questions About C Variables
What are variables in C?
Variables in C are named objects used to store typed values. A declaration associates a variable name with a type, and a definition provides the storage for the object.
What is the difference between declaring and initializing a C variable?
Declaring a variable introduces its name and type. Initializing it supplies its first value as part of its definition. For example, int count; defines an uninitialized local variable, while int count = 0; defines and initializes it.
What is the difference between local and global variables in C?
A local variable is declared within a function or block and has block scope. A variable defined outside all functions has file scope and is commonly called global. File-scope variables also have static storage duration.
What happens if a C variable is not initialized?
An uninitialized automatic variable has an indeterminate value, and reading it can cause undefined behavior in common cases. An object with static storage duration receives zero initialization when no explicit initializer is provided.
Does C have only 32 keywords?
The statement that C has 32 keywords refers to the C90 language standard. Later C standards introduced additional keywords, so the applicable set depends on the C standard selected by the compiler.
TutorialKart.com