Variable Syntax and Naming Conventions
In this tutorial, we will learn how to create a variable in the C programming language and the rules for naming variables.
In this tutorial, we will learn how to create a variable in the C programming language and the rules for naming variables.
To create a variable in C, follow this syntax:
data_type variable_name = value;
Or
data_type variable_name;
C is a strongly typed language, so specifying the variable’s type is mandatory.
Examples:
int var = 10;
char ch = ‘A’;
float f;
You can create multiple variables in a single line using this syntax:
data_type variable1, variable2, variable3;
Or
data_type variable1 = value1, variable2 = value2, variable3 = value3;
Example:
int var1 = 10, var2 = 20, var3 = 30;
In the above example, three variables of type ‘int’ are defined in the same line.
When naming variables in C, you need to follow certain rules:
Rule #1: Variable names can only contain letters, digits, and underscores. Special symbols are not allowed. For example, age
, var23
, first_name
are all valid names, but @ge
, var$34
, ch*43
are invalid.
Rule #2: Variable names can start with a letter or an underscore, but not with a digit. For example, var23
is valid, but 23var
is invalid.
Rule #3: Whitespace is not allowed within variable names. Use underscores to separate words in a variable name. For example, first_name
is valid, but first name
is not valid.
Rule #4: Variable names cannot be any of the keywords in C. Keywords are special words with predefined meanings. There are a total of 32 keywords in C. Here is the table containing all the keywords:
auto | double | int | struct |
---|---|---|---|
break | else | long | switch |
case | enum | register | typedef |
char | extern | return | union |
continue | for | signed | void |
do | if | static | while |
default | goto | sizeof | volatile |
const | float | short | unsigned |
Make sure not to use any of these keywords as variable names in your program. If the compiler reports an error related to variable names, you can refer to the above table to check if your variable name matches any of the keywords.
Leave a comment