Open In App
Related Articles

Can We Call an Undeclared Function in C++?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn’t list argument types.
If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn’t compile and generates errors.

In the following example, the code will work fine in C, 

C

// C Program to demonstrate calling an undeclared function
#include <stdio.h>
 
// Argument list is not mentioned
void f();
 
// Driver Code
int main()
{
    // This is considered as poor style in C, but invalid in
    // C++
    f(2);
    getchar();
    return 0;
}
 
void f(int x) { printf("%d", x); }

                    

Output
2

Time Complexity: O(1)

Auxiliary Space: O(1)

 However if run the above code in C++, it won’t compile and generate an error, 

C++

// CPP Program to demonstrate calling an undeclared function
#include <bits/stdc++.h>
using namespace std;
 
// Argument list is not mentioned
void f();
 
// Driver Code
int main()
{
    // This is considered as poor style in C, but invalid in
    // C++
    f(2);
    getchar();
    return 0;
}
 
void f(int x) { cout << x << endl; }

                    

Output

prog.cpp: In function ‘int main()’:
prog.cpp:13:8: error: too many arguments to function ‘void f()’
    f(2);
       ^
prog.cpp:6:6: note: declared here
void f();
     ^

Time Complexity: O(1)

Auxiliary Space: O(1)


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads