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

#include

using namespace std;

int main() {

string name;

cout << "Tell me your name: "<

getline(cin, name);

sayHello ();

return 0;

}

void sayHello(string nameToGreet){

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

}

Why would the above program fail?

Possible Answers:

nameis not the right type.

There is no problem.

sayHellodoesn't exist at the point it is called.

sayHelloshould not be of typevoid.

nameToGreetwas never defined.

Correct answer:

sayHellodoesn't exist at the point it is called.

解释:

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

Learning Tools by Varsity Tutors