#Day5 'C' coding challenge

#Day5 'C' coding challenge

 What is the output of the below program?

int *call(); void main() { int *ptr; ptr=call(); clrscr(); printf("%d",*ptr); } int * call() { int x=25; ++x; return &x; }

The above program tests several scenarios:

1. Pointers
2. Pointer to local variable
3. Is clrscr() allowed in modern day C programming?
4. clrscr() is part of which library?
5. Function call and return value

--------------------------------------------------------
To start,
ptr is an integer pointer
call() is a function which which returns integer pointer (int *)
The integer pointer return value of call() is assigned to pointer ptr.

When call() is called, internal to the function, local variable 'x' is declared and and pre-increment of x is done where x becomes 26.
The address of that variable 'x' (&x) is passed as return value 

Now the ptr has value of address of 'x'
When *x is printed, it prints the value of local variable 'x' which is 26.
so, the output is 26.

Normally, the scope of the local variable is within the function.
As, the address of that variable is passed outside the function, the scope of 'x' is extended beyond a function.
---------------------------
clrscr() is used by old MS-DOS systems.
Engineers who started Turbo C must have used clrscr() which is part of conio library.
Modern compilers doesn't support clrscr()

Post a Comment

0 Comments