Variables in C : Declaration, naming rules, and assigning values during declaration. Includes examples.
What is variables in C language :
A name given to a memory location where any constant value is stored.
They are like labeled boxes that hold information, and the content of these boxes can be changed during the program's execution.
Rules for defining a variable in C :
Letter, number and the underscore(_) cab be used.
Spaces are NOT allowed.
Reserved keywords are NOT allowed.
Can't start with a digit.
Case is significant, num is different variable to Num.
Valid variable names : int bharti, float bharti123, char bharti_24;
Invalid variable names : $bharti, int 24bharti, char long;
Syntax to Declaration :
Before using a variable in C, you must declare it by specifying the variable's data type and name.
This can be done by using the syntax:
data_type variable_name;
For example, you can declare an integer variable named "age" by writing:
int age; // Declares a variable named 'age' of type integer
This declaration tells the compiler to allocate memory for an integer variable named "age" that can store whole numbers. Remember, following the rules for variable naming in C is crucial to ensure your code runs smoothly.
Syntax to Initialize :
You have the option to provide an initial value to a variable when declaring it. This means assigning a starting value to the variable at the time of declaration. This can be done by using the syntax:
data_type variable_name = value;
By initializing a variable during declaration, you set its value right from the start, making it ready for use with the assigned initial value.
Example :
int age = 30; // Declares and initializes 'age' with the value 30