Can any one solve this Problem...!!!

Try to solve this.....It's a nice program.....

#include<stdio.h>

void change()

{

/*Write something in this function so that the output of printf in main function should give 5 . Do not change the main function */ }

void main()

{

int i=5;

change();

i=10;

printf("%d",i);

}

Please reply to this if u found the solution...... :slight_smile:

Thanks,
-baba

A solution involving portable C eludes me! I naturally rejected the idea of having change() locate its return address on the stack and alter it to step over the i=10 statement. The precise location of the return address and even whether to increment it or decrement it and certainly by how much can vary from system to system. There is really no guarantee that the return address will be stored on the stack or even that there is a stack. I admit that I don't know of any currently marketed unix systems without a stack or that move the PC backwards. But I also don't know of any standard prohibiting them. These days we are in transistion from 32 bit to 64 bit architectures. Most versions of unix currently support executables in either architecture. So the change() function would need to detect the length of the return address as well.

But the other problem that I see with this involves agressive optimization. There is no indication that i is accessible to change() or is otherwise aliased or volatile. So there is no reason that the compiler writer could not legally choose to emit code that operates like...
i=10;
change();
printf("%d",i);
Whether or not that would happen would probably depend on the optimization level selected and the compiler used, and whether or not the resulting executable is intended to interact with a symbolic debugger.

So if you have a portable solution, I would love to see it!

how about this godawful hack?

#include<stdio.h>

void change()

{
    printf("5\n");
    fflush(stdout);
    fclose(stdout);
}

int main()
{

    int i=5;    
    change();    
    i=10;    
    printf("%d",i);
    return 0;
} 

And yea, I know I'm not changing the output value of i, for which no obvious even remotely portable solution occurs to me.

:smiley:
Certainly portable!

Thanks Jim....

this is not an acceptable solution,

since it was different
thought of sharing this...

#include<stdio.h>

void change()

{
#define printf(a,b) printf(a,b/2)
}

void main()

{

int i=5;

change();

i=10;

printf("%d",i);

}

Very clever!

   Good!

Very very Impressive...!!! :slight_smile:

-baba