Reputation: 41
consider following code:
#include <stdio.h>
int main( )
{
int a ;
a = message( ) ;
printf("--%d",a);
}
message( )
{
printf("--%d",printf ( "\nViruses are written in C" ));
return ;
}
I am getting output as:(in GCC)
Viruses are written in c--25--4
My explanation: return ;
statement returns the value in the Accumulator,the value returned by the latest printf
is stored in the accumulator...
is this correct or not?
Upvotes: 2
Views: 211
Reputation: 158469
You are invoking undefined behavior by returning nothing from a value returning function though. If we look at the draft C99 standard section 6.8.6.4
The return statement says:
[...] A return statement without an expression shall only appear in a function whose return type is void.
You should really have no expectations on how this should run but you can make some good guesses as Deep C presentation demonstrates in several sections but I would never do any of this in a production environment.
If you had warnings enabled you should have seen several informative messages, for example gcc
provides the following warnings:
warning: implicit declaration of function ‘message’ [-Wimplicit-function-declaration]
warning: return type defaults to ‘int’ [enabled by default]
warning: ‘return’ with no value, in function returning non-void [enabled by default]
You are also relying on implicit return types are no longer allowed since C99 but compilers like gcc
do support them even in C99 mode. So if that is the case then message
will have an int
implicit return type.
Upvotes: 1
Reputation: 106012
It returns nothing. It will terminate your function only. But as your function has no return type in C89 its return type implicitly converted to int
, but it is not legal in C99 and latter and this will invoke undefined behavior.
If a non-
void
function reaches the end of its body--that is, it fails to execute areturn
statement--the behavior of the program is undefined if it attempts to use value returned by the function.
Some compilers will issue a warning:
control reaches end of non-void function
Upvotes: 0
Reputation: 281495
The behaviour is undefined.
The reason you're seeing the 4
is that your code happened not to overwrite the register used to return values from functions (eg. eax
on 32-bit Intel) between the printf
that prints --%d
in message
(which printed the four characters --25
) and the final printf
in main
.
Upvotes: 3