Skip to content
Related Articles

Related Articles

Can We Call an Undeclared Function in C++?

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 21 Jun, 2022
Improve Article
Save Article

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)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!