Ad

Chapter - 4: Functions

Point out the errors, if any, in the following programs.


Ad
B
Sections
1
Exercises

(a)

#include<iostream>

using namespace std;


int main()
{
	int a = 30;
	f();
	return 0;
}

void f()
{
	int b = 20;
}

Error: f() is not declared. A function must be declared or defined before it is being called.


(b)

#include<iostream>

using namespace std;

void f()
{
	int b = 20;
}

int main()
{
	int a = 30;
	f();
	return 0;
}

No Error.


(c)

#include<iostream>

using namespace std;

int f(int, int);
int f(int, int);

int main()
{
	int a ;
	a = f(10, 30);
	cout << a;
	return 0;
}

void f(int x, int y)
{
	return x + y;
}

Error: Return type do not match of f() in declaration and definition.


(d)

#include<iostream>

using namespace std;

int main()
{
	void fun1();
	void fun2();
	fun1();
	return 0;
}

void fun1(void)
{
	fun2()
	cout << endl << "Hi...Hello";
}

void fun2(void)
{
	cout << endl << "to you";
}

Error: fun2() is not declared/define in this scope.  As fun2() is declared in main(), so it is unknown in other functions, ( fun1() in this case ).


(e)

#include<iostream>

using namespace std;
void f(int, float);
int main()
{
	f();
	return 0;
}
void f(int i = 10, float a = 3.14)
{
	cout << i << a;
}

Error: If the definition and declaration of a function are separate, so default argument must be passed in the time of declaration.


(f)

#include<iostream>

using namespace std;

void f(int = 10, int  = 20, int = 30);
void f(int, int);

int main()
{
	f(1, 2);
	return 0;
}

void f(int x, int y, int z)
{
	cout << x << endl << y << endl << z;
}

void f(int x, int y)
{
	cout << x << endl << y;
}

Error: As both the overloaded function can be called in this calling in main, so the compiler will in ambiguity.

Ad

© 2024 Garbage Valuegarbage value logo