C Programming - Functions - Discussion

Discussion Forum : Functions - Point Out Errors (Q.No. 3)
3.
Point out the error in the program
#include<stdio.h>

int main()
{
    int a=10;
    void f();
    a = f();
    printf("%d\n", a);
    return 0;
}
void f()
{
    printf("Hi");
}
Error: Not allowed assignment
Error: Doesn't print anything
No error
None of above
Answer: Option
Explanation:

The function void f() is not visible to the compiler while going through main() function. So we have to declare this prototype void f(); before to main() function. This kind of error will not occur in modern compilers.

Discussion:
14 comments Page 2 of 2.

Dawood Ibrahim Bhat said:   7 years ago
Dear friends, true explanation for this option in my view is that:

integer (a) is assigned equal to a void function, since void returns nothing, therefore in the program above we are equating an integer to nothing, it is wrong, we can never equate an integer equal to void. Hence this kind of assignment is not allowed.

And declaring a function before defining it is important ....but in C we can declare functions in main function, use int instead of void for f().and also add a return statement to the block of f() function.

Thanks.

Nitesh said:   5 years ago
@Mayank.

In modern Compilers, you never get this error. And in your case, You get 2 means In printf statement you have 2 characters 1=H and 2=i so it returns 2 .

Nishu said:   5 years ago
I think, the error here is that the value of type void can't be assigned in type int
a=f();

Here return type of f() is void and a is of int type.

Anomie said:   3 years ago
Can anyone help me to clear this in detail?


Post your comments here:

Your comments will be displayed after verification.