Thursday 26 December 2013

Magic Numbers

magic numbers


     Magic number are the unknown numbers used while writing a program , magic numbers should not be used in any c program as:-

1.  They degrade the quality of the program
2. They make it difficult to understand the program
3. They make program hard to modify in future
4. Even you cannot determine why you used the particular number ,if you go through your program after sometime.

 see the image below , this program contains magic numbers .................

now in the for loop it is difficult to determine why the loop ends at 10 ????


now see a better version of same program which uses pre processor directive( line 5 ). preprocessor does not end with ' ; ' (look again in line 5 ), preprocessor are used as a text editor, actually it is small program that runs before the compiler and replaces 'SIZE' with '10' throughout the program. so if you put ';' then it will replace 'SIZE ' with ' 10 ; ' and that will give you unexpected errors ( or even worst you would not get an error ).


there is still a magic number , yes 0, but most of the programmers don't take it as a magic number. Make sure your c program does not have magic numbers in future.
        

1 comment:

  1. any question regarding magic numbers feel free to ask...:)

    ReplyDelete