Computer Science : Method Declarations

Study concepts, example questions & explanations for Computer Science

varsity tutors app store varsity tutors android store

Example Questions

Example Question #1 : Method Declarations

#include <iostream>

#include <string>

using namespace std;

 

int main() {

string name;

cout << "Tell me your name: "<<endl;

getline(cin, name);

sayHello();

 

return 0;

}

 

void sayHello(string nameToGreet){

cout << "Hello, " << nameToGreet << "!"<< endl;

}

Why would the above program fail?

Possible Answers:

nameToGreet was never defined.

sayHello should not be of type void.

name is not the right type.

sayHello doesn't exist at the point it is called.

There is no problem.

Correct answer:

sayHello doesn't exist at the point it is called.

Explanation:

The compiler will read the program from top to bottom, and by the time it gets to the function call for sayHello in main, it will have no clue what sayHello is. Therefore an exception will be raised. To circumvent this issue, define sayHello before main, OR provide a function prototype before main to make the compiler aware of the appropriate signature for the sayHello function.

Learning Tools by Varsity Tutors

Incompatible Browser

Please upgrade or download one of the following browsers to use Instant Tutoring: