Variable Naming Rules
Part of the Fundamentals section of Coddy's C journey — lesson 12 of 63.
In C, variable naming rules are important to follow for creating valid and readable code. Here are the key rules:
- Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
- They must begin with a letter or underscore, not a digit.
- C is case-sensitive, so
myVariableandmyvariableare different.
- Keywords (like
int,float,return) cannot be used as variable names.
- No spaces or special characters (except underscore) are allowed.
Good practices for naming variables include:
- Use descriptive names that indicate the variable's purpose.
- Use camelCase or snake_case for multi-word names.
- Keep names concise but meaningful.
int age; // Good: starts with a letter
float _price; // Good: starts with an underscoreUse only letters, numbers, and underscores:
int item123; // Good: contains letters and numbers
float cost_per_unit; // Good: uses underscoreVariable names are case-sensitive:
int value;
int Value; // This is a different variable than "value"Avoid using C keywords:
int if; // Wrong: "if" is a keyword
int total; // Good: "total" is not a keywordChallenge
EasyWrite a program that declares and initializes two variables with valid names according to C naming rules.
The first variable should be an integer named "userAge" set to 25. The second variable should be a float named "item_price" set to 9.99.
Then print both variables using printf in the following format:
User age: 25
Item price: 9.99Cheat sheet
C variable naming rules:
- Can contain letters (a-z, A-Z), digits (0-9), and underscores (_)
- Must begin with a letter or underscore, not a digit
- Case-sensitive:
myVariableandmyvariableare different - Cannot use C keywords (like
int,float,return) - No spaces or special characters except underscore
Good naming practices:
- Use descriptive names
- Use camelCase or snake_case for multi-word names
- Keep names concise but meaningful
Valid variable names:
int age; // Good: starts with a letter
float _price; // Good: starts with an underscore
int item123; // Good: contains letters and numbers
float cost_per_unit; // Good: uses underscoreCase sensitivity example:
int value;
int Value; // Different variable than "value"Avoid C keywords:
int if; // Wrong: "if" is a keyword
int total; // Good: "total" is not a keywordTry it yourself
#include <stdio.h>
int main() {
// Declare and initialize two variables with valid names
// Print both variables
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Variables
Data TypesIntegerFloat - DoubleCharactersBooleansConstantsprintf BasicsVariable Naming RulesType Casting Part 1Type Casting Part 2Recap Challenge3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge