Computer Science : Method Declarations

Study concepts, example questions & explanations for Computer Science

varsity tutors app store varsity tutors android store

Example Questions

Example Question #21 : Programming Constructs

#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:

sayHello should not be of type void.

nameToGreet was never defined.

There is no problem.

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

name is not the right type.

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