Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why a function with returntype in c works with out return statement? [duplicate]

Tags:

c

Possible Duplicate:
Why can you return from a non-void function without returning a value without producing a compiler error?

void main()
{
    int y=0;
    clrscr();
    printf("%d\n",Testing());
    y=Testing();
    printf("%d",y);
    getch();
}
int  Testing()
{
    int x=100;
    //return x;
}

Result 
512
4

i am not returning any thing from the testing function still value is coming?

Another Question also

void main()
{
    char Testing();
    int y=0;
    clrscr();
    printf("%d\n",Testing());
    if(Testing())
        printf("if--exi");
    else
        printf("else--exi");
    getch();
}
char Testing()
{
    char y;
    //return y;
}

Result

0
if--exi

if printf is commented then result is

else--exi

why is it happening like that

like image 445
Nighil Avatar asked May 10 '11 16:05

Nighil


2 Answers

Why is your question tagged C and C++ at the same time, while the title specifically refers to C? These two languages are significantly different in this regard.

In C language such functions "work" because the language requires them to work. Why not? The function that is declared with some return type might still do some useful work (besides returning anything). So, not having a return statement in such a function is perfectly fine from the formal point of view. It is not a good programming practice though. The function will work as long as you are not trying to use the returned value (which the function didn't really return). You are trying to use that value, which makes the behavior of your code undefined. You are claiming that it "works". In reality it doesn't. What happens in this case and why - these questions have no answers. For all means and purposes your code's behavior is essentially random and unpredictable.

In C++ language functions that "forget" to return a value with a return statement always immediately lead to undefined behavior, regardless of whether the value is used by the caller or not.

like image 28
AnT Avatar answered Sep 19 '22 21:09

AnT


A function declared to return a value that reaches a path without a return has undefined behavior. You just got unlucky that it appeared to still be returning a semi-plausible value. The compiler assumes that a return is called in all exits from the function and that a return value will be available at a particular location.

In your second example effectively anything can happen, including returning different values each call.

g++ has a warning to detect this problem, and it's highly worth enabling.

like image 74
Mark B Avatar answered Sep 19 '22 21:09

Mark B