Every program has to deal with information or data now or then in its life span of operation. And the intended programming language has to support such data types for programmer convenience sake.
|
The C language offers in-built data types with certain rules imposed on them while using. To study data types means studying the data, how it is defined, how it is declared, how it is accessed, how to select proper data type, what is its storage length, and what all operations are allowed on it.
By this the language clears that any program variables, constants or data must be any of these two categories: in-built or user-defined types. Hence C language is also called as typed language, means while declaring any variable, constant or data programmer has to specify its data type compulsorily.
So, in C language if programmer stores greater value then specified by rule overflow may occurs. It is programmer job to properly declaring variables, constants with suitable data type, handling them properly and not expect compiler to raise any error about it.
Usually include file limits.h is used to limit programs MAX and MIN range and thus make the code run generally on any kind of computer.
//declaring variable with datatype
int sum ;
float avg;
char name[10];
//assigning proper value
sum = 1200;
avg = 15.8967;
strcpy(name,”Gandhi”);
//accessing with proper specifier
printf(“%d, %f, %s”, sum , avg, name);
Different Data Types
C includes simple or fundamental data types as well as derived types, which defined or constructed from the simple types.
Data Type | Description |
char | Type char objects are stored as one byte. |
int | The amount of storage reserved is system dependent. |
float | This real number typically allots 32 bits with 7 significant digits [10E-38 to 10E+38] |
double | This double precision float type is a 64-bit value. |
Character data type
Actually in C, character data type is assumed as sub range of integers and fits inside a byte. It takes one byte or 8-bits memory to store any ASCII character set element. They are signed characters [-128 to 127] and unsigned characters [0 to 255].
Programmer can use char data type to store ASCII character or 1-byte integer values. The basic four arithmetic operations are allowed on char data type are: + [addition], - [subtraction], / [division] and % [modulus=get remainder]. To read or to print char data type %c specifier is used.
char Gender = ‘M’ ;
char TempValue; //stores ASCII character or -124 to 125 values
TempValue = -110;
printf (“ %d “, TempValue+10);
TempValue = ‘s’;
printf (“ %c “, TempValue);
unsigned char response; //stores ASCII character or 0 to 225 values
response = 120%10;
Note that character constant ‘A’ [ASCII value=01000001] is not equal to string constant “A” [‘A’ + ‘\0’]. The string ”A” in terminated with NULL character whose ASCII value is 00110000 and does not equals to decimal digit zero or blank.
Integer data type
The integers or whole numbers take 2 byte data for their storage. The range modifiers short and long are used to limit the size of any given integer. Their type from default signed integers to unsigned integers can be changed using type modifiers.
Programmer can use integer data type to store signed or unsigned integers of 2 byte length in its data type variable. The basic four arithmetic operations are allowed on int data type are: + [addition], - [subtraction], / [division] and % [modulus=get remainder]. To read or to print unsigned int data type %u, signed int data type %d and signed long int data type %ld specifier is used.
unsigned int stadium_seats;
short int heartPulses;
unsigned short int stars_in_galaxy;
long int big-num =1234567890L;
unsigned long int population_2014;
or without int specifier as int is default datatype
unsigned letters; //it is actually unsigned int letters
long rope; //it is actually long int rope
unsigned short note; //it is actually unsigned short int note
Float & double data types
When single precision or fractional part storage is needed float data types are used. Floats are stored in four bytes and are accurate to about seven significant digits [E-38, E37]. In any computations with floating point numbers, errors of round-off or truncation are necessarily introduced.
Where large scale scientific or engineering computations are involved, the double declaration becomes the natural choice for program variables. The double specification allows the storage of double precision floating point numbers ( in eight consecutive bytes) which are held correct to 15 figures, and have a much greater range of definition than float [E-308,e307].
Note that all operations supported by C language are not allowed on Float & Double data types [it is true with integer only]. Only basic binary operators known as Arithmetic operators, + [addition], - [subtraction], / [division] holds good with both data type.
To access float data type use %e or %f or %g and use %lf for double data type value.
velocity of light in vacuum, 2,997925E10cm/sec
number of seconds in 400 years
population of planet earth, appr. 5.4 billion
value of Avogadro’s number, 6.0248E23
value of Planck’s constant, 6.61E-27
6,594,126,820,000,000,000,000=which is appr. mass value of earth, in tons
The include of <float.h> is necessary in the code where double and float data types are used.
What happens if data types are assign more than their range value?
If variables are assigning more than their maximum limit value, it will overflow [resets, starts from zero] and code may generate random result or compiler may raise warning while compiling.
Identifiers: names of storage locations
Identifiers are used as the general terminology for naming of variables, constants, functions and arrays. These user-defined names are nothing but address of memory locations.
- They must begin with a letter or underscore(_).
- They must consist of only letters, digits, or underscore. No other special character is allowed.
- It should not be a keyword.
- It must not contain white space.
- It should be up to 31 characters long as only first 31 characters are significant.
· Some examples of c identifiers:
/*variables: legal identifiers*/
int avg ; char keypress ; char student_name[10] ;
/*constants: legal identifiers*/
int PI = 3.142 ; char ENTERKEY ; char TITLE[10] ;
/*function name: legal identifiers*/
Sum_of_Int() ; age_Proof() ; getADCReading() ;
/*legal: poor identifiers*/
int Day1_7 ; char _getData ;
/*illegal identifiers*/
Tom’sAddress To-Do-List @rate 7AMWork $Spend Temp.var
/*keywords: invalid identifiers*/
void main() goto sin()
& address of operator or Referring variables by name and address
The declared data types are referred either by their name or by using address of operator. In the below code segment, salary is integer type variable and assigned by 125300 value [hence direct assignment] and in second case value is getting by keypad or user [so, &-address of operator is used to store it directly in its memory location].
int salary;
salary = 125300; //direct value assignment
printf(“Enter your salary:”);
scanf(“%d”, &salary); //directed to address of salary
Variables: Declarations
A variable is an object that may take on values of the specified type. Variables must be declared by specifying the data type and the identifier.
data type | identifier or variable name; |
int | salary; |
char | response; |
float | average; |
double | amount; |
long | lightyears; |
Actually, only declaration of variable makes its initial value to anything/garbage but zero and accidently using such variable in operations creates unpredictable result while running program.
But why to declare any variable, why not directly use them? Because C compiler maintains record of all elements in the code, and allows proper operations on it when needed. For example, to print integer value it has to know the stored number is valid integer number or not [by declaring it] and expects proper instruction from the code [by adding proper extraction command: %d].
int salary;
salary = 56850;
printf(“Salary: %d”, salary); //print salary value as decimal integer
There are two steps to carry out while dealing with variables: declaration and definition. Above first step is only declaration step. The next step definition actually allocates memory location to variable and is known as definition/ initialization step [using assignment operator or ‘=’ symbol].
Both steps, declaration and initialization/definition steps can be done in single line code.
data type | identifier or variable name; |
int | salary = 000; |
char | response=’y’; |
float | average=0.0; |
double | amount=000; |
long | lightyears=4.7000; |
In C language, many variable objects can be declared & initialized in single line code only if they are of same data type.
data type | identifier or variable name; |
int | salary = 000, year, i, j; |
char | response=’y’, ans; |
Note about Identifiers
Like natural language, writing program means writing code in some kind of artificial language. That means, c programs are made of its components, reserved keywords, library functions, constants and variables. By this program terminology restricts to some extent and narrows programmer identifier name choice. Programmer cannot use library function names or reserved keywords in his code. Also he has to plan the identifiers name according to his program’s subject domain, for example the program is about science terms he can use temperature, pressure, mass, isothermal expansion etc.
Constants and Volatiles
As name implies, constants are objects whose value does not change during the execution of the code. They are of any built-in data type and are declared & defined in single line code. It is done in two ways: using #define pre-processor term and const key word. Some of the examples of constant declarations using pre-processor are as follows:
#define IDENTIFIER | replaced_by_this_term |
#define TRUE | 1 |
#define PI | 3.14159 |
#define YES | 0 |
#define DEFAULT_MOBILENO | +919901234567 |
#define TITLE | “BASIC ELECTRONICS” |
#define MAX_USERS | 100 |
Since #define is preprocessor directive and taken care before compiling, does not end with semicolon. |
While defining constants, it is not necessary to mention the data type as in variable declaration [see above table]. While declaring constant using const keyword it is mandatory to mention the data type as shown in below. This is because they are type safe constants, i.e., they are constant with specified data type.
const variablename = value; |
const string Title = “LINUX, GCC and Beginner”; |
const int dozen = 12; |
const float velocityOfLightInVacuum = 2997925e10; const int velocityOfSoundInAir = 750; |
Since const is a keyword and processed by compiler, it needs semicolon. |
ANSI C has another modifier called volatile, to explicitly indicate variables whose values may change, and which must be accessed for a possibly changed value whenever they are referenced.
Casting or Type Conversion
The C language provides a mechanism which explicitly converts one type object into other data type. The general form of casting is
/* for explicit casting: x value is converted into float value */
int x ;
------
(float) x;
/*with assignment operator: before division sum value is converted into float*/
int sum , count ;
float avg ;
------
avg = (float) sum / count ;
Casting is frequently use when integers are passed as arguments to mathematical functions.
Range Modifiers & Storage Classes
As it is said data type modifiers short, long, signed and unsigned are used to modify default range to desired one.
unsigned char response;
long int no_of_files_open;
short int adcValue;
Similarly, storage class modifiers are used to limit the scope of any variable or constant throughout file or within code block. It is done using four keywords: auto, static, register and extern.
auto: The default storage classes’ life is within code block it is declared. It is also call internal or local variable.
static: A local variable as auto, but it exist even after program moves to calling function and retain its value for further function call.
register: It is compiler’s job to decide which object should be stored in register [as fixed number of registers is available]. Accessing of these object values is fast as register are integral part of CPU.
extern: The global variables available to entire project are declare by this name in calling file.
As you know, systems are made of many source files each with their local variables and global variables.
In such files it is necessary to restrict the object/variables lifetime and scope only to its file or global to system wide operations. It is done using storage class modifiers: auto, static, register and extern. The general form of declaration of Storage class is as follows:
register char response;
static int no_of_files_open;
extern int adcValue;
Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).This null character indicates the end of the string. Strings are always enclosed in double quotes. Whereas character is enclose in single quotes in C and C++ language.
/*string initialized at declaration: character wise*/
char string [5] = { ‘H’ , ‘e’ , ‘l’, ‘l’, ‘o’};
/*string initialized at declaration: at once*/
char string [5] = “Hello” ;
/*string initialized at declaration: at once but not length mentioned*/
char string [ ] = “Hello” ;
Previous Page | Main Contents | Next Page |
No comments:
Post a Comment