Saturday, 10 August 2013

Variable in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Variable |

A variable is named location in memory. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in previous chapter, there will be following basic variable types:

Type Description
char Integer type, Single byte of storage
int Natural size of the integer for the machine usually 2 bytes
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.

 


| Variable Declaration |

All variables must be declared before we use them in C program, although certain declarations can be made implicitly by content. A declaration specifies a type, and contains a list of one or more variables of that type as follows:

type var_list;

Here, type must be a valid C data type including char, int, float, double, or any user defined data type etc., and var_list may consist of one or more identifier names separated by commas. Some valid variable declarations along with their definition are shown here:

int a,b,c;
char ch;
float f;
double d;

We can initialize a variable at the time of declaration as follows:

int a=10;

An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists some where else in the program. A variable can be declared multiple times in a program, but it must be defined only once. Following is the declaration of a variable with extern keyword:

extern int a;

| Variable Initialization |

var_name=value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:

type var_name=value;

#include<stdio.h>
void main()
{
int a,b,c;
a=10;
b=5;
c=a+b;
printf("\nSum of a and b is:%d",c);
}

 

No comments:

Post a Comment