A function with an int or void return type can be called before declaring and defining?

StackOverflow https://stackoverflow.com/questions/18482887

  •  26-06-2022
  •  | 
  •  

Question

I read in "The C Programming Language ANSI edition by Kernighan and Ritchie" that if I call a function with a return type either int or void inside another function before actually declaring/defining it, it should work perfectly. But when I run it on codeblocks I still get a warning.

#include<stdio.h>
#include<conio.h>
int main()
{
    display();
}
void display()
{
    printf("Hello World\n");
}

The warning being: "Conflicting types for display".

But if i change the program to:

#include<stdio.h>
#include<conio.h>
void display()
{
    printf("Hello World\n");
}
int main()
{
    display();
}

It works without any warnings. Why is that? Please help.

Was it helpful?

Solution

You are calling display before declaring it. When you do so the compiler makes an assumption over the type of the return value. It assumes that it is int. But when you define the function you use a return value of type void which is the conflict.

It's been a very long time since anybody thought it was sound to call functions that have not been declared. So, declare all functions before calling them. It's best to configure your compiler so that it rejects attempts to call functions that have not been declared.

OTHER TIPS

you are calling the function before declaring it. If you have read the book somewhere there is mentioned function prototype deceleration.

#include<stdio.h>
#include<conio.h>
void display(void);  // function prototype decleration
int main()
{
    display();
}
void display()
{
    printf("Hello World\n");
}

Hope this helps so always define a prototype.

Use a function prototype before the main function like so:

void display();

int main()
{
    display();
}

void display()
{
    printf("Hello World\n");
}

If the function is called when the compiler hasn't seen its prototype, it assumes that the return type is int.

However, this feature(called implicit function declaration) is removed since C99 and you should never rely on it.

Using a function declaration is clearly a better choice:

void display(void);
int main(void)
{
    display();
}
void display(void)
{
    printf("Hello World\n");
}

Only int return type is assumed by default not void. You must refer to a newer standard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top