Saturday 23 December 2017

Variables in C Programming Language - Geeks4Coding

Variables in C


A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

Variable Declaration:


A typical variable declaration is of the form:

data type variable_name;

for multiple variables declaration
data type vr1_name, var2_name, var3_name;

A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.

Variable declaration and definition

Variable declaration refers to the part where a variable is first declared or introduced before its first use. Variable definition is the part where the variable is assigned a memory location and a value. Most of the times, variable declaration and definition are done together.

#include <stdio.h>
//extern int c;
int main()
{
char a = 'a'; // declaration and definition of variable 'a123'

float b;// This is also both declaration &definition/assigned garbage value.

printf("%c \n", a,c);

return 0;
}

 

Keyword extern is explained here.

Lvalues and Rvalues in C


There are two kinds of expressions in C:
 

Lvalue 

Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
 

Rvalue 

The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
 

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −
 

int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error


No comments:

Post a Comment

Thank you for your Time. Keep Learning

Geeks4Coding

Contributors

Popular Posts