I am a beginner in C programming language, recently I have started learning functions, I have studied that functions use keyword return to return a value in the caller function. For example the following program.
int getVal(){
return 1000;
}
int main(){
int x = getVal();
printf("x = %d",x);
return 0;
}
will print x = 1000
but I am confused that (under turbo C compiler 32 bit) why the following program is producing output as x = 1000 too. Please explain.
int get_val(){
_AX = 1000;
}
int main(){
int x = get_val();
printf("x = %d",x);
return 0;
}
in getval(), 1000 is stored in accumulator,and getval() will give compile time warning that function should return a value,then in the main, x will be assigned the value returned or stored in the accumulator which is 1000, that's why it will print x=1000.
The "return value" is returned in a particular register (defined by the "ABI", the Application Binary interface, which describes how compilers should generate their code), in most x86 systems, that is EAX (32 bit) or AX (16 bit) [not saying _AX isn't actually EAX internally].
This compiler obviously supports using a "register" directly by naming it _AX. So by loading the [E]AX register with a value, we are essentially returning this value.
This definitely won't work in any other compiler, although inline assembler can achieve the same thing.
According to TC compiler (32 bit), the returned value of a function is stored in Accumulator (AC), and it can be accessed in TC compiler using _AX, so when you write:
means that you are placing value 1000 inside Accumulator, and when the function completes its execution and the control reaches to the caller function, then the value of Accumulator is checked, and in this case this value will be stored in x.
here the statement
would be simply
but this would be in your case only, means in (TC 32 bit windows compiler), it may or may not work for other compilers.
In C here, _AX is a pseudo register. And when you do
AX=1000
, this value1000
is taken from the AccumulatorBut it may not work as expected in GCC compiler
Compile and Run the following program in Turbo C, you will get 35 as output. It may not work in other compilers.
Assume the address of a = 1200. Assume the address of video memory = 5500;
This is the way of execution takes place. After copying the value 35 to location 1200, AH retains the value 35.
Then
printf("%d")
tries to get the value from AH and sends to video memory to display it on screen.If we use
printf("%d %d", age, salary)
, the value of age transfered to AH before using that value to send to video memory. Then the value of salary is moved to AH then send to video memory.Assume, Address of age = 1200; Address of salary= 1202; Address of video memory = XXXX; (It will changed according to no. of chars printed on the screen, dont think much about this address value)
I hope this will help to understand the solution for the given program.