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.


The Syntax

Creating a Single Variable

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; 

Creating Multiple Variables in a Single Line

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.


Naming Conventions

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:

autodoubleint struct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
continueforsignedvoid
doifstaticwhile
defaultgotosizeofvolatile
constfloatshortunsigned

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

Leave a comment

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

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.