Home > OS >  Why can't we call a function in C before declaring it but we can do it in Java?
Why can't we call a function in C before declaring it but we can do it in Java?

Time:02-26

C Program:

#include<iostream>

int main(){
    sayHello();
}

void sayHello(){
    std::cout << "Hello\n";
}

Output:

main.cpp: In function 'int main()':
main.cpp:4:5: error: 'sayHello' was not declared in this scope
     sayHello();
     ^~~~~~~~

Java Program:

public class Main
{
    public static void main(String[] args) {
        sayHello();
    }
    
    public static void sayHello(){
        System.out.println("Hello");
    }
}

Output:

Hello

Is it just because Java provides support to resolve any dependencies among functions during compilation but C does not. If yes, Is there a specific reason that C did not provide this feature?

CodePudding user response:

This is because code becomes available only after its declaration. In your C example, you could declare sayHello() before defining main() like this:

#include <iostream>

void sayHello();

int main() {
    sayHello();
}

void sayHello() {
    std::cout << "Hello\n";
}

What's different about Java is that every file contains a class. When a class is defined, first all of the class members are declared, and only then their definition is considered. So in your Java example, first class Main is defined with methods main(String[]) and sayHello(), and only then it's defined that the main method calls sayHello that is already declared. You can replicate this behaviour in C by creating a class like in Java:

#include <iostream>

class Main {
public:
    static void main() {
        sayHello();
    }
    static void sayHello() {
        std::cout << "Hello\n";
    }
};

int main()
{
    Main::main();
}

CodePudding user response:

the difference in the code above is that in C you have two methods and main method is run before the sayHello() method due to which compiler does not know that sayHello exists.

Whereas in Java you have a class which contains those methods. So when you run the code the class is created along which all the methods are known to the compiler, then when main method is run it is able to execute sayHello() method.

I hope it clarifies your question.

  • Related