Campus Buzz

all the stuffs learned while preparin for campus will be posted here!


Monday, May 15, 2006


C is amusing!

OK! why I'm sayin this b'coz I discovered some real amusing facts about C.let's start declarations and initializations.

what do u think the size of a and b if
char far *a, *b;

Let me guess: 2 2.
but the right answer is 4 bytes for a and 2 bytes for b.
Reason: far pointer would require 4 bytes of memory. Now what the hell is far pointer and why it is required?

The answer is related to memory model of earlier IBM PC. The PC, when running in real mode, is able to address only 64K at any time using16-bit addresses, referred to as near pointers. This limitation is a problem because many programs and their data are larger than 64K. To address more than 64K, it is necessary to use segments and offsets, which are forms of 24-bit addresses. If the compiler is told to use segments, it generally creates two problems: Segment arithmetic will cause your application to be slightly slower, and the size of the program will be larger.Using segments and offsets is referred to as far pointers.

Now enough of historical reasons, lets look the other problems which will definitely stir ur head...

Consider this program,
extern int i;
2 4 or error, if error ,what kind of error...

The answer it will give the error like: C:\DOCUME~1\General\LOCALS~1\Temp\cc0gcaaa.o(.text+0x3b)
In function `main': [Linker error] undefined reference to `i' now, what caused tis error: Whenever C compiler find the variable declared extern, it assumes that this variable is declared somewhere else. This program is syntantically correct, but when the compiler tries to link the program it finds the refernce of the extern variable which is not defined elsewhere. This code can be debugged in this way to compile successfully.

extern int i;

the value of i inside main() function is 100 whereas outside the function, the value is 20.
Here, u just saw the extern variable can have many definitions within the program. What about global variable? can they enjoy the same liberty? fortunately, the answer is No. Global variable can have many declarations but only one definition. The same is applicable to functions definiton and declaration.


Post a Comment

<< Home