Variables in C Language: A variable in C language defines the what type of data it can be stored in the memory. And we can also change the value of a variable during execution of a program. It is a way to represent memory location through a symbol so that it can be easily identified.
Syntax: type variable_list;
C Variables
Example: average, name, height, employee, etc.,
#include<stdio.h> extern int a, b; extern int c; int main() { int a, b; a = 7; b = 14; c = a + b; printf("Sum is : %d \n", c); return 0; }
Output: Sum is: 21
Datatype of Variable
Variables can store different types of data which can hold. They are like char, int, float, double, void.
Rules to name variables:
- A variable name must not start with a digit.
- It can consist of alphabets, digits and special symbols like underscore _
- Space and blanks are not allowed in variables.
- Keywords are not allowed as a variable name.
- Upper & lower case names are treated as different because C is case sensitive, so keep it in the lower case.
Variable Definition in C
It defines the compiler how much memory has to be stored. And the variable definition defines a specific data type and contains a list of one or more variables of that type.
Syntax: type variable_list
Example
int i, j, k; char c,ch; float f, salary; double d;
Rules for defining variables
- Variable can have alphabets, digits, and underscore.
- Variable name can start with the alphabet, and underscore only. It can’t start with a digit.
- No whitespace is allowed within the variable name.
- A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Declaring, Defining and Initializing a Variable in C
Deceleration must be done before they are used in the program. While declaring you should know some things regarding this.
- Deceleration tells the compiler what the variable name is.
- It specifies what type of data the variable will holds.
- A variable is declared using the extern keyword, outside the main () function.
Example
#include<stdio.h> extern int a, b;/*Variable declaration:*/ extern int c; extern float f; int main () { int a, b;/*Variable declaration:*/ int c; float f; a = 10; b = 20; c = a + b; printf("value of c : %d \n", c); f=70.0/3.0; printf("value of f : %f \n", f); return 0; }
Output
value of c: 30
value of f: 23.333334
L values and R values in C
There are two types of conditions in C i.e. L value and Rvalue.
lvalue
lvalueExpressions which are referred to a memory location are called “lvalue” expressions. lvalue may disappear as either the left-hand or right-hand side of an assignment
rvalue
rvalue refers to the data value that is stored at some address in memory. And rvalue is an expression that cannot have a value assigned to it means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
Example
int g = 15;//valid statement 20 = 30; // invalid statement; would generate compile-time error