sojin wrote:
#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 main() // C++ does NOT have 'void main'
{
int i=5;
change();
i=10;
printf("%d",i);
}
There is no solution to your homework problem in the Standard C++, AFAICS.
Since the value that printf outputs is a local [to 'main'] variable,
nothing that another function can do would access that variable if you
don't pass its address or a reference to it into that function. Passing
that reference (or the address) would require changing the 'main'
function, which would mean not satisfying the requirement not to change
the 'main' function.
There is one way to make the _program_ to output 5 (instead of 10) but
the output will not be generated by the call to 'printf' in 'main'. You
could write
void change()
{
printf("5");
exit(0);
}
which basically causes the program to quit before even getting of the
'change' function. However, that goes against the "output of printf
in main function should give 5" because the output is from a different
call to printf.
Using non-standard means you can tweak the stack to make the 'change'
function return to 'main' in the place _after_ the "i=10" statement,
but that wouldn't be done in C++.
V