Wednesday 20 May 2015

illegal Programming behavior in C

Every Programmer knows how to program. Computer Programming is a well defined set of task under some rules that when applies communicate with the Computer to solve certain Problem. But sometimes Computer Programming needs to snatch some rights that were not given or we can say the lenient Programming design allows the Programmer to do some task that are not governed by the rules defined by the Programming Language.

C programming is also binded with certain rules that we follow to make an error free program. These rules must be followed but just some C enthusiast learners know that there are some rules that provide the flexibility according to programming.

Suppose we need an array of Integers to store 10 numbers corresponding to Students Roll no - XX (1-10) , but now we need to store the number for the student with Roll no - 25 what we would do, either we would take up a new array and try to add it to the previous array and store this new extended array in a third array. but there is one more way to do that.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/* Extending the size of Array */
#include <stdio.h>
int main()
{
 int array[10];
 int i=-4;
 array[0]=44;
 array[9]=67;
 array[5]=34;
 array[10]=89;
 array[25]=99;
 array[-4]=77;
 printf("\n %d",array[-4]);
 printf("\n Forward Iteration: ");
 for(i=0;i<sizeof(array);i++)
 {
  printf("\nindex= %d, value=%d",i,array[i]);
 }
 return 0;

}

Look at the statements at line no 11 and 12. Many people might be thinking the array index out of bounds exception and compile time error in C but this code would surely works.

Now most of the people would assume how can an array of size 10 be referenced with the array at an index or offset 25 or -4. But C programming allows us to do this . As we have stated during the variable declaration that we would use an array with 10 blocks of memory , but when we reference array with offset 25 or -4, the array take up the memory illegally , we do not demanded earlier but forcefully take up the space, So this is called the illegal behavior in C programming.




0 comments:

Post a Comment

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel