Master C++

Your first program

6 / 235
Contents

Contents

Master C++

0 of 235 complete

7 min read

Values in, an answer back

How a named block of instructions is handed values to work on, and how the answer gets out again.

Every program so far has been one block of instructions called main, doing the same thing from top to bottom and printing as it went. The problem sets at the end of this section are shaped slightly differently, and the difference is worth a few minutes here rather than a puzzled hour there.

main is a function, a named block of instructions, and functions have a whole section to themselves later on. Two facts about them are needed now. A function can be handed values to work on. And it can hand one value back to whoever asked.

The values it is handed

The names inside the round brackets after a function's name are the values it will be given, each written with the kind of thing it is in front of it, exactly the way a variable is. They are called parameters. Inside the body they behave like variables that already have values in them, and those values came from whoever wrote the call.

Try CodeC++

Change one of the names inside main and run it again. Nothing in greeting needs touching: it is written once, in terms of name and time, and works on whatever it is handed.

The answer it hands back

return ends the function there and then and sends one value back. In main that value goes to the operating system, which is why it is 0. Anywhere else it goes to the place the call was written, and the call is replaced by the value, which is why std::cout << greeting("Jo", "evening") prints a greeting rather than the word greeting. The kind written in front of the function's name says what sort of value comes back: std::string above, int for main.

Try CodeC++

Change 90 to 1440 and run it again. Then try adding a third line of your own that asks for a different number of minutes.

That is all you need. Each problem set below hands you the function's first line already written, with the parameters named and the kind of answer stated, and asks you to fill in the body and return the right value. The return ""; or return 0.0; sitting in the starting code is a placeholder: it makes the file compile before you have written a thing, and it is there to be replaced.

Why does std::cout << secondsIn(2); put 120 on the screen rather than the word secondsIn?

The call is carried out first. secondsIn(2) runs the function, which returns 120, and the whole call is then replaced by that number, so << is handed 120 and nothing else. Quotation marks would change it completely: std::cout << "secondsIn(2)"; sends those characters as written, because text is never worked out.

All lessons in Master C++