简体   繁体   中英

What happens when we assign a function call return value with return type void to a int variable?

#include<stdio.h>
int main()
{
   //void foo();
   int c= 5;
   c=foo();
   printf("\n%d",c);
   return 0;
}
void foo()
{
  printf("I am foo");
}

When I am commenting the prototype declaration then it gives the output:

I am foo

8

With prototype it gives the error saying:

void value not ignored as it ought ought to be.

My question is, what is internally happening which result into the output when there is no prototype declaration? What is the reason behind it?

I am using Dev C++ editor with TDM-GCC 4.9.2 64bit compiler.

The sole reason this is built successfully is the implicit int rule (now removed in the latest revision of the C standard).

The compiler sees no forward declaration of foo , so it assumes that its return type is int. It then proceeds to build and call your void foo() . After all is said and done, the behavior of your program is undefined.

Gcc compiler give warning and successfully run and return number of character with whitespace but some compiler give an error.

pp.c:10:6: warning: conflicting types for ‘foo’ [enabled by default]
 void foo()
      ^
pp.c:6:6: note: previous implicit declaration of ‘foo’ was here
    c=foo();

when there is no prototype declaration

Well, that is invalid C.

To elaborate,

  • Point 1: You cannot have a function called which is not declared earlier. It is against the C standard rule. Note

  • Point 2: As soon as you add the forward declaration, you'll be getting compilation error, as a void type cannot be the RHS operand of an assignment operator and this is a constraint violation for assignment operator.


Note:

Pre C99, it was allowed to have a function being called without the prototype known, it was assumed that the function will be returning an int and will be accepting any number of parameters. However, this is precisely forbidden as per C99 and later, as the "implicit int rule" is removed from the standard. (Refer Foreword, paragraph 5, _"remove implicit int"_ in C99 standard) .

In your case, for legacy reasons, the compiler still supports the implicit int rule, so it compiles fine, however, the assumption by compiler and the actual function definition is a mismatch. This invokes undefined behavior .

Quoting C11 , chapter §6.5.2.2, Function calls

If the function is defined with a type that is not compatible with the type (of the expression) pointed to by the expression that denotes the called function, the behavior is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM