Saturday, September 8, 2012

Data Types in C

 A program usually contains different types of data types and need to store the values being used in the program. C language is rich of data types. A C programmer has to employ proper data type as per his requirements. C has different data types for different types of data and can be broadly classified as
  •   Primary Data Types
  •   Secondary Data Types
 
Primary Data Types
 
Integer Data Types
 Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767(that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number.

Syntax:
int <variable name>;

int num1;
short int num2;
long int num3;
Example: 5, 6, 100, 2500.
Integer Data Type Memory Allocation:


Floating Point Data Types:
The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number.The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.
Syntax:
float  <variable name>;
float num1;
double num2;
long double num3;                                                       
Example:    9.125, 3.1254.
Floating Point Data Type Memory Allocation:

 
Character Data Type:
Character type variable can hold a single character and are declared by using the keyword char. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from -128 to 127.
Syntax:
char <variable name>; 
char ch = ‘a’;
Example: a,b,g,S,j.
Void Type:
The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. The void data type is usually used with function to specify its type.
Constants : 
Constants are of fixed values that do not change during the execution of a program. There are various types of constants.














Integer constants : 
An integer constant refers to a sequence of digits. There are three types of integer constants, namely, decimal integer, octal integer and hexadecimal integer.
Decimal integer 
 consists of a set of digits from 0 to 9, preceded by an optional + or – sign. Examples,      123     -321    0          64932
Octal integer
consists of a set of digits from 0 to 7, with a leading 0. Examples, 037     0       0437         0551
 A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also includes letters from A to F or from a to f. The letters represents the numbers from 10 to 15.Examples,            0X2     0x9F   0Xbcd    0x
Real constants : 
 Real constants are used to represent quantities that are very continuously, such as distances, temperature etc. These quantities are represented by numbers containing fractional parts. Examples,      0.00832          -0.75               33.337
Single character constants
A single character constants contains a single character enclosed within a pair of single quote marks. Example, ‘5’         ‘X’       ‘;’
String constants : 
 A string constant contains a string of characters enclosed within a pair of double quote marks. Examples,    “Hello !”         “1987”            “?....!”
 Backslash character constants : 
 C supports some special backslash character constants that are used in output functions. For example
Constants                                                    Meaning
     ‘\a’                                                       audible alert (bell)
     ‘\n’                                                       new line
     ‘\?’                                                       question mark

Variables:
Variables are simply names used to refer to some location in memory - a location that holds a value with which we are working. It may help to think of variables as a placeholder for a value. You can think of a variable as being equivalent to its assigned value.
Features:
  •  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.Variables must always be declared at the top before any other commands are used. Now let's declare an integer variable called a and a character variable called b

int main()
{
int a;
char b;
return 0;
}
C keeps a small set of keywords for its own use only.These keywords are given below:
 auto             break           case          char          const            continue           default          do
 double         else             enum         extern        float             for                   goto              if
 int                long            register       return        short           signed               sizeof     static
struct           switch         typedef      union          unsigned     void                  volatile          while  

Identifiers:    Identifiers" or "symbols" are the names you supply for variables, types,labels, and functions in your program. Identifier names must differ in case and spelling from any keywords. Identifiers provide names for the given language elements: 1.Functions 2.Function parameters 3.Macros and macro parameters 4.Type definitions 5.Objects 6.Labels 7.Enumerated types and enumerators 8.Structure and union names example:
int main()
{
int result;

if ( result != 0 )
printf_s( "Bad file handle\n" );
}

 Variable Declaration
Variables are of three different types which are as follows:
1.  Global Variable
2.  Local Variable  
3.  Static Variable
Global Variable: 
The C programming language has an extensive system for declaring variables of different types. The rules for the more complex types can be confusing at times, due to the decisions taken over their design. The principal decision is that the declaration of a variable should be similar, syntactically, to its use (declaration reflects use) . Declare it outside of all the functions if you want to declare a global variable. The function will use the variable that was declared within it and ignore the global one,if a variable of the same name is declared both within a function and outside of it.
Local Variable:      
  Inside the specific function that creates them,these variables only exist. They are unknown to to the main program and to the other functions. In this case,they are normally implemented using a stack. Local variables cease to exist once if the function that created them is completed. Each time a function is executed or called,they are recreated.
The following program demonstrate the use of global and local variables.
#include <stdio.h>
int counter = 0; /* global because we are outside all blocks.*/
int func(void);
main()
{
counter++; /* global because it has not been declared within this block */
printf("counter is %2d before the call to func\n", counter);

func(); /* call a function. */
printf("counter is %2d after the call to func\n", counter);
}

int func(void)
{
int counter = 10; /* local variable because it has declared within this block */
*/ printf("counter is %2d within func\n", counter);
}

static variables 
Another important feature of the variable scoping is the static variable. In a local function scope,a static variable exists only , but it does not lose its value when program execution leaves this scope. Consider the example which is given below:
#include <stdio.h>
main()
{
Test();
}
function Test()
{
int a = 0;
printf("a is %d within func\n", a)
a++;
}
Since every time the function is called it sets a to 0 and prints "0",this function is quite useless . The a++ which increments the variable serves no purpose since as soon as the function exits then a variable disappears. The a variable is declared static to make a useful counting function which will not lose track of the current count:
#include <stdio.h>

main()
{
Test();
}
function Test()
{
static int a = 0;
printf("a is %d within func\n", a)
a++;
}

Storage classes:
 Every C variable has a storage class and a scope. The storage class determines the part of memory where storage is allocated for an object and how long the storage allocation continues to exist. It also determines the scope which specifies the part of the program over which a variable name is visible, i.e. the variable is accessible by name. The are four storage classes in C are automatic, register, external, and static.
 auto :
auto is the default storage class for local variables.

    int Count;
  auto int Month;
}
 extern:
 extern defines a global variable that is visable to all object modules. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously def
 file1.h
 extern int global_counter;  /* Declaration of globalvariable */

file2.h
 #include "file1.h"  /* Declaration of global counter available here */
/*Global  Variable defined here */
int global_counter = 20;    /* global variable initialized */
int incrementhere(void) { return global_counter++; }


file3.h
 #include "file1.h"
#include <stdio.h>
void use_intern_variable(void)
{
    printf("Global counter: %d\n", global_counter++);
}

 register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location). { register int Miles; } some example programs 1.
#include <stdio.h>
  int main() 
 {
  int x;
  printf( "Declare x first" );
  return 0;
 }

2.
#include <stdio.h>
int main()
{
  int this_is_a_number;
  printf( "Please enter a number: " );
  scanf( "%d", &this_is_a_number );
  printf( "You entered %d", this_is_a_number );
  getchar();
  return 0;
}

Some important questions: 

Q.What is the difference between declaring a variable and defining a variable?
 Declaration of a variable in C hints the compiler about the type and size of the variable in compile time. Similarly, declaration of a function hints about type and size of function parameters. No space is reserved in memory for any variable in case of declaration. Example: int a; Here variable 'a' is declared of data type 'int' Defining a variable means declaring it and also allocating space to hold it. We can say "Definition = Declaration + Space reservation". Example: int a = 10; Here variable "a" is described as an int to the compiler and memory is allocated to hold value 10.
 Q.Difference between pass by reference and pass by value?
  Pass by reference passes a pointer to the value. This allows the callee to modify the variable directly.Pass by value gives a copy of the value to the callee. This allows the callee to modify the value without modifying the variable. (In other words, the callee simply cannot modify the variable, since it lacks a reference to it.)

No comments:

Post a Comment