Friday, 5 July 2013

C Variable Types | C Programming Tutorial pdf

A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types

  • Local Variables
  • Global Variables


Local Variables:

Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.

When a local variable is defined - it is not initalised by the system, you must initalise it yourself.

When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output

   main()
   {
      int i=4;
      int j=10;
   
      i++;
   
      if (j > 0)
      { 
         /* i defined in 'main' can be seen */
         printf("i is %d\n",i); 
      }
   
      if (j > 0)
      {
         /* 'i' is defined and so local to this block */
         int i=100; 
         printf("i is %d\n",i);      
      }/* 'i' (value 100) dies here */
   
      printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/
   }
   
   This will generate following output
   i is 5
   i is 100
   i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;

You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables:

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initalised automatically by the system when you define them!

Data Type  Initialser
int                    0
char                  '\0'
float                    0
pointer          NULL
If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

   int i=4;          /* Global definition   */
   
   main()
   {
       i++;          /* Global variable     */
       func();
       printf( "Value of i = %d -- main function\n", i );
   }

   func()
   {
       int i=10;     /* Local definition */
       i++;          /* Local variable    */
       printf( "Value of i = %d -- func() function\n", i );
   }

   This will produce following result
   Value of i = 11 -- func() function
   Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.

C Storage Classes | C Programming Tutorial pdf

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.

There are following storage classes which can be used in a C Program

  • auto
  • register
  • static
  • extern

auto - Storage Class

auto is the default storage class for all local variables.

{
            int Count;
            auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

register - Storage Class

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;
}
Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count;
        int Road;

        {
            printf("%d\n", Road);
        }
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.

   void func(void);
   
   static count=10; /* Global variable - static is the default */
   
   main()
   {
     while (count--) 
     {
         func();
     }
   
   }
   
   void func( void )
   {
     static i = 5;
     i++;
     printf("i is %d and count is %d\n", i, count);
   }
   
   This will produce following result
   
   i is 6 and count is 9
   i is 7 and count is 8
   i is 8 and count is 7
   i is 9 and count is 6
   i is 10 and count is 5
   i is 11 and count is 4
   i is 12 and count is 3
   i is 13 and count is 2
   i is 14 and count is 1
   i is 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memoriese void as nothing. static variables are initialized to 0 automatically.

Definition vs Declaration : Before proceeding, let us understand the difference between defintion and declaration of a variable or function. Definition means where a variable or function is defined in realityand actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.

There is one more very important use for 'static'. Consider this bit of code.

   char *func(void);

   main()
   {
      char *Text1;
      Text1 = func();
   }

   char *func(void)
   {
      char Text2[10]="martin";
      return(Text2);
   }
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify

    static char Text[10]="martin";
The storage assigned to 'text2' will remain reserved for the duration if the program.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL the program files. 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 defined.

When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files.

File 1: main.c

   int count=5;

   main()
   {
     write_extern();
   }

File 2: write.c

   void write_extern(void);

   extern int count;

   void write_extern(void)
   {
     printf("count is %i\n", count);
   }
Here extern keyword is being used to declare count in another file.

Now compile these two files as follows

   gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.

Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value

C CONSTANTS AND LITERALS | C Programming Tutorial pdf

Constants:

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer literals:

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x
or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. T he suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
212                    /* Legal */
215u                  /* Legal */
0xFeeL             /* Legal */
078                 /* Illegal: 8 is not an octal digit */
032UU          /* Illegal: cannot repeat a suffix */
Following are other examples of various type of Integer literals:
85                  /* decimal */
0213             /* octal */
0x4b            /* hexadecimal */
30               /* int */
30u            /* unsigned int */
30l            /* long */
30ul         /* unsigned long */

Floating-point literals:

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can  represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while  representing using exponential form, you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:
3.14159                           /* Legal */
314159E-5L                   /* Legal */
510E                              /* Illegal: incomplete exponent */
210f                              /* Illegal: no decimal or exponent */
.e55                             /* Illegal: missing integer or fraction */

Character constants:

Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
T here are certain characters in C when they are proceeded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here you have a list of some of such escape sequence codes

Following is the example to show few escape sequence characters:
#include <stdio.h>
int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces following result:
Hello   World

String literals:

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
Y ou can break a long lines into multiple lines using string literals and separating them using whitespaces. Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining Constants:

T here are two simple ways in C to define constants:
1. Using #define preprocessor.
2. Using const keyword.

1. The #define Preprocessor
Following is the form to use #define preprocessor to define a constant:
#define identifier value
Following example explains it in detail:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50

The const Keyword:

Y ou can use const prefix to declare constants with a specific type as follows:
const type variable = value;
Following example explains it in detail:
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50

C Operator Types | C Programming Tutorial pdf

What is Operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.


  • Arithmetic Operators
  • Logical (or Relational) Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators


Lets have a look on all operators one by one.

Arithmetic Operators:

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable B holds 20 then:

Show Examples

Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then:

Show Examples

Bitwise operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

Show Examples

There are following Bitwise operators supported by C language

Assignment Operators:

There are following assignment operators supported by C language:

Show Examples

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

Misc Operators:

There are few other operators supported by C Language.

Show Examples

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

Postfix operators, which follow a single operand.

Unary prefix operators, which precede a single operand.

Binary operators, which take two operands and perform a variety of arithmetic and logical operations.

The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.

Assignment operators, which assign a value to a variable.

The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.


C Flow Control Statements | C Programming Tutorial pdf


C provides two sytles of flow control:

  • Branching
  • Looping

Branching is deciding what actions to take and looping is deciding how many times to take a certain action.

Branching:

Branching is so called because the program chooses to follow one branch or another.

if statement

This is the most simple form of the branching statements.

It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.

NOTE: Expression will be assumed to be true if its evaulated values is non-zero.

if statements take the following form:
Show Example

? : Operator:

The ? : operator is just like an if ... else statement except that because it is an operator you can use it within expressions.

? : is a ternary operator in that it takes three values, this is the only ternary operator C has.

? : takes the following form:

Show Example

if condition is true ? then X return value : otherwise Y value;

switch statement:

The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read.

Show Example

switch( expression )
     {
        case constant-expression1: statements1;
        [case constant-expression2: statements2;]    
        [case constant-expression3: statements3;]
        [default : statements4;]
     }
Using break keyword:

If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword.

Try out given example Show Example

What is default condition:

If none of the listed conditions is met then default condition executed.

Try out given example Show Example


Looping:

Loops provide a way to repeat commands and control how many times they are repeated. C provides a number of looping way.

while loop

The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.

Basic syntax of while loop is as follows:

Show Example

while ( expression )
{
   Single statement 
   or
   Block of statements;
}
for loop:

for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:

Basic syntax of for loop is as follows:

Show Example

for( expression1; expression2; expression3)
{
   Single statement
   or
   Block of statements;
}

In the above syntax:

expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
do...while loop

do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.

Basic syntax of do...while loop is as follows:

Show Example

do
{
   Single statement
   or
   Block of statements;
}while(expression);

break and continue statements:

C provides two commands to control how we loop:

  • break -- exit form loop or switch.
  • continue -- skip 1 iteration of loop.

You already have seen example of using break statement. Here is an example showing usage of continue statement.

This will produce following output:

C Input and Output | C Programming Tutorial pdf

Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.

Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data.

Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions

printf() function

This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ).

Try following program to understand printf() function.

#include <stdio.h>

main()
{
  int dec = 5;
  char str[] = "abc";
  char ch = 's';
  float pi = 3.14;

  printf("%d %s %f %c\n", dec, str, pi,  ch);
}
The output of the above would be:

       5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character.

A complete syntax of printf() function is given in C - Built-in Functions

scanf() function

This is the function which can be used to to read an input from the command line.

Try following program to understand scanf() function.

#include <stdio.h>

main()
{
  int x;
  int args;

  printf("Enter an integer: ");
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
}
Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x.

This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.

Enter an integer: 20
Read in 20

C Pointing to Data | C Programming Tutorial pdf

A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier.
  • There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators.
  • When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable.
  • When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.
Here is an example to understand what I have stated above.




This will produce following result.



Pointers and Arrays:
The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example:

   char *y;
   char x[100];
y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of

   y = &x[0];
   y = x;
Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following:

   *(y+1)  gives x[1]
   *(y+i)  gives x[i]

and the sequence

   y = &x[0];
   y++;

leaves y pointing at x[1].

Pointer Arithmetic:

C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:

  int x = 5, *ip = &x;
  ip++;
On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.

Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.
Using Pointer Arithmetic With Arrays:
Arrays occupy consecutive memory slots in the computer's memory. This is where pointer arithmetic comes in handy - if you create a pointer to the first element, incrementing it one step will make it point to the next element.



This will produce following result:



See more examples on Pointers and Array


Pointers and const Type Qualifier:

  • The const type qualifier can make things a little confusing when it is used with pointer declarations.
  • The below example
       
As you can see, you must be careful when specifying the const qualifier when using pointers.

Modifying Variables Using Pointers:

You know how to access the value pointed to using the dereference operator, but you can also modify the content of variables. To achieve this, put the dereferenced pointer on the left of the assignment operator, as shown in this example, which uses an array:



This will produce following result:



Generic Pointers: ( void Pointer )

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different types at different times.

Try the following code to understand Generic Pointers.

NOTE-1 : Here in first print statement, the_data is prefixed by *(int*). This is called type casting in C language.Type is used to caste a variable from one data type to another datatype to make it compatible to the lvalue.

NOTE-2 : lvalue is something which is used to left side of a statement and in which we can assign some value. A constant can't be an lvalue because we can not assign any value in contact. For example x = y, here x is lvalue and y is rvalue.

However, above example will produce following result:

the_data points to the integer value 6
the_data now points to the character a