C LANGUAGE VARIABLES

C Language Variables

What is variable?

Variables or symbolic variables are the names of storage location of computer memory whose values may vary during execution of a program.
These memory locations may contain integer, real or character constant.
There are always two values associated with a symbolic variable.
 

•    Its data value (read value) stored at some location in memory and is referred as variable’s rvalue.
 

•    Its location value (address value) the address at which its data value is stored and is referred as variable’s lvalue.

Overview on variables:

Data is stored in a computer's memory. The memory system comprises of uniquely numbered cells called memory addresses. We need to know the address where something is stored in order to retrieve it and work on it. A programming language frees us from keeping track of these memory addresses by substituting names for them. These names are called variables. Variables are descriptive names for the memory addresses.
 

Before we use a variable in C we must declare it. We must identify what kind of information will be stored in it. This is called defining a variable. Variables must be declared at the start of any block of code, but most are found at the start of each function. A variable must be defined to be one of the legal C data types. When a variable is defined it is not automatically initialized, it is the responsibility of the programmer to initialize this to a start value.

Variable Declaration in C:

All variables must be declared before we use them in C program, although certain declarations can be made implicitly by content. To declare a variable you specify its name and data type it can store. The variable declaration always ends with a semicolon (;) A declaration specifies a type, and contains a list of one or more variables of that type as follows:
type variable_list;
 

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

int    i, j, k;

char   c, ch;

float f, salary;

double d;

You can initialize a variable at the time of declaration as follows:
int    i = 100;
An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists somewhere 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    i;
Though you can declare a variable multiple times in C program but it can be declared only once in a file, a function or a block of code.

Assigning Values to Variables:

A variable can be considered as a box that can hold a single value. However, initially the content of a variable (or a box) is empty. Therefore, before one can use a variable, it must receive a value. Do not assume the compiler or computer will put some value, say 0, into a variable. There are at least three ways to put a value into a variable:
 

•    initializing it when the program is run
 

•    using an assignment statement
 

•    reading a value from keyboard or other device with a READ statement.
Variables may have values assigned to them through the use of an assignment statement.
Such a statement uses the assignment operator =
This operator does not denote equality.  It assigns the value of the right-hand side of the statement (the expression) to the variable on the left-hand side.

Examples:
    Diameter = 5.9;
    Area = length * width;

Note that only single variables may appear on the left-hand side of the assignment operator
Initializing a variable is only done exactly once when the computer loads your program into memory for execution. That is, all initializations are done before the program starts its execution. The use of un-initialized variables may cause unexpected result.
Some examples are:
Int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */

Purpose of Variables:

•    Variables in C are memory locations with help of which we can be assigned values and are given names.
 

•    To store data in memory for later use, we use variables.
 

•    In C, a variable must have to be declared before it can be used.
 

•    You can declare Variables at the start of any block of code, but most are found at the start of each function.
 

•    Most local variables are destroyed on return from that function and created when the function is called.
 

•    A declaration begins with the type, followed by the name of one or more than one variables.

Naming Restrictions:

•    All variables must be declared before they can appear in executable statement.
•     A declaration consists of a data type followed by one or more variable names separated by commas.

Example: int a, b, c;

•    Variables can be distributed among declarations in any fashion. The above declaration can be written as
int a;
int b, c;
•    Integer type variables can be declared to be short integer for smaller integer quantities or long integer for larger integer quantities.

Example:

short int a, b, c;
long int a, b, c;
•    An integer variable can also be declared to be unsigned by writing unsigned int.

Example: unsigned int;
•    C programmers generally agree on the following conventions for naming variables.
o    Begin variable names with lowercase letters
o    Use meaningful identifiers
o    Separate “words” within identifiers with underscores or mixed upper and lower case. 
                   Examples:  surfaceArea  
   surface_Area
   surface_area
o    Be consistent!
•    Use all uppercase for symbolic constants   (used in #define preprocessor directives).
             Examples: #define PI 3.14159
                    #define AGE 52
•    C is case sensitive. It matters whether an identifier, such as a variable name, is uppercase or lowercase.
Example: area
                            Area
                            AREA
                             ArEa. Are all seen as different variables by the compiler.

Scope of variables: Once declared, an object can be hidden locally by another declaration.
Global variable: A global variable (declared outside a function) has an application scope, meaning that it can be accessed by any part of the application, assuming it is properly declared in each file. When using the static keyword on its declaration, a global variable has a file scope, meaning that it can be accessed only inside the file where it is declared. In any other file, the same declaration will not access the same object. It means that a static declaration at file level is hiding a global level variable declared with the same name in another file. Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable in these functions, and must be declared as such. The declaration must be preceded by the word extern. The declaration is required so the compiler can find the type of the variable without having to search through several source files for the declaration.
Global and external variables can be of any legal type. They can be initialized, but the initialization takes place when the program starts up, before entry to the main function.
Local variable: A local variable (declared inside a function) has a function scope, meaning that it can be accessed only inside that function, even if declared with the static keyword. A function level object will hide any object declared at file or global level with the same name. Another class of local variable is the static type. A static can only be accessed from the function in which it was declared, like a local variable. The static variable is not destroyed on exit from the function; instead its value is preserved, and becomes available again when the function is next called. Static variables are declared as local variables, but the declaration is preceded by the word static. Static variables can be initialized as normal; the initialization is performed once only, when the program starts up.

 static int counter;

Block Scope: A Block is a set of statements enclosed within left and right braces ({and} respectively). Blocks may be nested in C (a block may contain other blocks inside it). A variable declared in a block is accessible in the block and all inner blocks of that block, but not accessible outside the block. If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the pint of declaration by inner block.

Types of variables:

In C, there are different types of variables for different types of data. Integer numbers, real numbers and character data each have their own data type.

Integer variables:

C has five kinds of integer. An integer is a whole number (a number without a fractional part). In C, there are a limited number of integers possible; how many depends on the type of integer. In arithmetic, you can have as large a number as you like, but C integer types always have a largest (and smallest) possible number.


char: The char type stores a single ASCII character. Characters are enclosed in single quotes. For example, 'a' or 'A' or '2'.
short: The short data type is useful for small integers. The amount of space allocated is decided by the compiler. If the compiler allocates 16 bits, a short can store numbers from -32767 to 32768.
int: int is the default type for integer data such as 232, or -3. The amount of storage space allocated will depend on the compiler. Generally, int will have the same amount of storage as either short or long .
long: The long type allocates twice as much storage as short. If the compiler allocates 32 bits for a long, the value can range over approximately +/- 2 billion.

These integer types differ in the size of the integer they can hold and the amount of storage required for them. The sizes of these variables depend on the hardware and operating system of the computer.

Floating point variables:

Floating point numbers are numbers with a decimal point. There are different sizes of floating point numbers in C. The float type can contain large floating point numbers with a small degree of precision, but the double-precision double type can hold even larger numbers with a higher degree of precision. All floating point mathematical functions built into C require double or long float arguments (long float variables are generally the same as double variables on GNU systems), so it is common to use float only for storage of small floating point numbers, and to use double everywhere else.
Here are the floating point variable types available in C:

float: A float variable is appropriate for most real numbers such as 3.5 or 2.667.

double: Double allocates twice as much memory for the number as float. It is short for double precision. Variables of type double should be used when you need very precise results or are doing many calculations with a variable that involve numbers of different magnitudes.

Array variables:

The array is another kind of variable that is used extensively in C.An array is an identifier that refers to a collection of data items that all have a same name. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer. When we declare array, it allocates contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have random locations. So this is the most important difference between a variable and an array.

•    As with all variables, an array needs to be declared. The syntax for declaring an array is to start with the type (as usual), then the name for your array, followed by brackets ( [ ] ) containing an integer value that specifies the number of items that can be stored into the array. The code above declares a variable called "list" that can hold 3 integers.
 

•    In the declaration, the value in the brackets must be a constant (either a literal, as in the code above, or a #define value).
 

•    Note that as with other variables, declaring an array does not initialize its values. Your code will need to set a value for each item in the array.
 

•    To access an item in the array (to set or read it), use the variable name followed by brackets containing the index of the desired item. Note that index values start at 0, not 1. This means that if there are n items in an array, the valid index values are from 0 (the first item) to n-1(the last item).

Declaration of an Array: 


Arrays must be declared before they can be used in the program. Standard array declaration is as
type variable_name[length of array];
Here type specifies the variable type of the element which is going to be stored in the array. In C programming language we can declare the array of any basic standard type which C language supports. For example
double height[10];
float width[20];
int min[9];
char name[20];
In C Language, an array starts at position 0. The elements of the array occupy adjacent locations in memory. C Language treats the name of the array as if it were a pointer to the first element this is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accessed anywhere from within the program. So
m=height [0];
Variable m will have the value of first item of array height.
Initializing Arrays: Initializing of array is very simple in c programming. The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name. Here is an example which declares and initializes an array of five elements of type int. Array can also be initialized after declaration.

Types of Arrays:

1.    One dimension array (Also known as 1-D array):

Declaration of One Dimensional Array:

Syntax: data_type array_name [width];

Example: int roll [8];

In our example, int specifies the type of the variable, roll specifies the name of the variable and the value in bracket [8] is new for newbie. The bracket ([ ]) tells compiler that it is an array and number mention in the bracket specifies that how many elements (values in any array is called elements) it can store. This number is called dimension of array.
2. Two Dimensional Array (2D Array): In C language it is possible to have more than one dimension in an array. In this tutorial we are going to learn how we can use two dimensional arrays (2D arrays) to store values. Because it is a 2D array so its structure will be different from one dimension array (1D array). The 2D array is also known as Matrix or Table, it is an array of array. See the 2D array image, in that image each row is an array.

Declaration of 2D array:

Syntax: data_type array_name [row_size][column_size];

Example: int arr [3][3]; So the above example declares a 2D array of integer type. This integer array has been named arr and it can hold up to 9 elements (3 rows x 3 columns).
3. Multi dimensional array (3D Array): C allows array of two or more dimensions and maximum numbers of dimension a C program can have is depend on the compiler we are using. Generally, an array having one dimension is called 1D array, array having two dimensions called 2D array and so on. So in C programming an array can have two or three or four or even ten or more dimensions. More dimensions in an array means more data it can hold and of course more difficulties to manage and understand these arrays. A multidimensional array has following syntax:

Syntax: 


type array_name [d1][d2][d3][d4]………[dn];
Where dn is the size of last dimension.
Example: int table [5][5][20];
float arr [5][6][5][6][5];
 

In our example array “table” is a 3D (A 3D array is an array of arrays of arrays.) array which can hold 500 integer type elements. And array “arr” is a 5D array which can hold 4500 floating-point elements. Can see the power of array over variable? When it comes to hold multiple values in a C programming, we need to declare several variables (for example to store 150 integers) but in case of array, a single array can hold thousands of values (depending on compiler, array type etc).

Arrays Limitations: 


Because names of arrays represent just a pointer to the beginning of the array, we have some limitations or "problems."

•    No Array Out of Bounds Checking. For example:
int ia[2] = {0, 1};
printf("%d ", ia[2]);
The above code would default, because you are trying to look at an area of memory not inside the array memory allocation.
 

•    Array Size Must be constant or known at Compile-time.
 

•    Arrays cannot be Copied or Compared. Why because they are pointers.
 

•    Array Index Type must be Integral.

0 comments:

Post a Comment