Search

2.x — Chapter 2 summary and quiz

Quick Summary

A function is a reusable sequence of statements designed to do a particular job. Functions you write yourself are called user-defined functions.

A function call is an expression that tells the CPU to execute a function. The function initiating the function call is the caller, and the function being called is the callee or called function. Do not forget to include parenthesis when making a function call.

The curly braces and statements in a function definition are called the function body.

The return type of a function indicates the type of value that the function will return. The return statement determines the specific return value that is returned to the caller. This process is called return by value. Functions can have a return type of void if they do not return a value to the caller. Failure to return a value from a non-void function will result in undefined behavior.

The return value from function main is called a status code, and it tells the operating system (and any other programs that called yours) whether your program executed successfully or not. By consensus a return value of 0 means success, and a positive return value means failure.

A function parameter is a variable used in a function where the value is provided by the caller of the function. An argument is the specific value passed from the caller to the function. When an argument is copied into the parameter, this is called pass by value.

C++ does not define whether function calls evaluate arguments left to right or vice-versa.

Function parameters and variables defined inside the function body are called local variables. The time in which a variable exists is called its lifetime. Variables are created and destroyed at runtime, which is when the program is running. A variable’s scope determines where it can be accessed. When a variable can be accessed, we say it is in scope. When it can not be accessed, we say it is out of scope. Scope is a compile-time property, meaning it is enforced at compile time.

Refactoring is the process of breaking down a larger function into many smaller, simpler functions.

Whitespace refers to characters used for formatting purposes. In C++, this includes spaces, tabs, and newlines.

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. To write a forward declaration for a function, we use a function prototype, which includes the function’s return type, name, and parameters, but no function body.

A definition actually implements (for functions and types) or instantiates (for variables) an identifier. A declaration is a statement that tells the compiler about the existence of the identifier. In C++, all definitions serve as declarations. Pure declarations are declarations that are not also definitions (such as function prototypes).

Most non-trivial programs contain multiple files.

When two identifiers are introduced into the same program in a way that the compiler or linker can’t tell them apart, the compiler or linker will produce a naming collision. A namespace guarantees that all identifiers within the namespace are unique. The std namespace is one such namespace.

The preprocessor is a process that runs on the code before it is compiled. Directives are special instructions to the preprocessor. Directives start with a # symbol and end with a newline. A macro is a rule that defines how input text is converted to a replacement output text.

Header files are files designed to propagate declarations to code files. When using the #include directive, the #include directive is replaced by the contents of the included file. When including headers, use angled brackets when including system headers (e.g. those in the C++ standard library), and use double quotes when including user-defined headers (the ones you write). When including system headers, include the versions with no .h extension if they exist.

Header guards prevent the contents of a header from being included more than once into a given code file. They do not prevent the contents of a header from being included into multiple different code files.

Quiz time

Be sure to use your editor’s auto-formatting feature to keep your formatting consistent and make your code easier to read.

Question #1

Write a single-file program (named main.cpp) that reads two separate integers from the user, adds them together, and then outputs the answer. The program should use three functions:

  • A function named “readNumber” should be used to get (and return) a single integer from the user.
  • A function named “writeAnswer” should be used to output the answer. This function should take a single parameter and have no return value.
  • A main() function should be used to glue the above functions together.

Show Hint

Show Hint

Show Solution

Question #2

Modify the program you wrote in exercise #1 so that readNumber() and writeAnswer() live in a separate file called “io.cpp”. Use a forward declaration to access them from main().

If you’re having problems, make sure “io.cpp” is properly added to your project so it gets compiled.

Show Solution

Question #3

Modify the program you wrote in #2 so that it uses a header file (named io.h) to access the functions instead of using forward declarations directly in your code (.cpp) files. Make sure your header file uses header guards.

Show Solution


3.1 -- Syntax and semantic errors
Index
2.13 -- How to design your first programs

137 comments to 2.x — Chapter 2 summary and quiz

  • bastenko

    At Question 3, i copied the code, but it doesn't compile.

    In main.cpp: undefined reference to 'readNumber()' , in line 5.

  • NitoCore

    is this good?

  • MiesterMind

    In visual studios whenever I create a .h file from the header section, it uses #pragma once rather than using #ifndef, #define , and #endif. It seems as if it does the same thing, so I was wondering what the difference between the two was.

  • John

    Is it good practice to define headers in every file that a function from said header is used? For example, I didn't have to #include "io.h" in io.cpp, but the answer key has it included.

    • nascardriver

      If a source file uses something from a header, include that header.
      If you define a source file, include the corresponding header so that you don't have to repeat all the includes that were in the header.

  • Tony

    Chapter 2 finished, 20.07.2020!

    Just one question. In the first quiz I did the same as the solution, with a 'tiny' difference.

    The other questions went well. Thanks again!

    • nascardriver

      Calculating `x + y` directly in the function call can be faster. There's probably no different when using integers, but keep this in mind when you get to larger types and more complex programs.

  • Luce

    Hi, quick question.

    My original solution had 2 variables defined in main(), in the same way as the solutions listed:

    but after I had finished, I changed it to simply:

    I figured the variables were only getting used once and this made the code more concise, but I'm wondering if there's a preference here.
    Thanks ahead!

    • nascardriver

      It is undefined in which order your `readNumber` function will be called if you don't use variables. This doesn't matter for addition, but for other operations the order is important.

      You don't know if the user will be asked for the minuend or subtrahend first. If they're asked for the subtrahend first, the result is wrong.

  • Amir

    io.h

    io.cpp

    main

  • Kai

    My only question is, why do I need to include the header in the io.cpp?
    Including it in main.cpp makes sense for me, but why I need to include the io.h aswell in the io.cpp?
    In io.cpp the functions are declared and defined why should i need a extra declaration in io.h for it.

    It compiles without #include io.h in io.cpp but I saw in your solution you had it included.

    And btw thank you very much for this website!

    main.cpp

    io.cpp

    io.h

  • Ejaz Hussain

    i have even went far xD for exercise 1
    #include <iostream>

    int readNumber(){
        std::cout << "Enter a number: ";
        int num{};
        std::cin >> num;
        return num;
    }

    void writeAnswer(int x){
        std::cout <<"Result: " << x << '\n';
    }

    int main(){
        writeAnswer(readNumber() + readNumber());
        return 0;
    } // and yah here we go in least lines, while following all the three steps

  • Tommy

    io.h
    #ifndef IO_H
    #define IO_H

    int readNumber();
    void writeAnswer(int z);

    #endif

    io.cpp
    #include <iostream>
    #include "io.h"

    int readNumber()
    {
        int x{};
        std::cout << "Please enter an integer: ";
        std::cin >> x;
        return x;
    }

    void writeAnswer(int z)
    {
        std::cout << "The sum is " << z << '\n';
    }

    main.cpp
    #include "io.h"

    int main()
    {
        int x{ readNumber() };
        int y{ readNumber() };
        writeAnswer(x + y);
        return 0;
    }
    //#include "io.h"

    Above is my code ,could anyone tell me why isnt my code working? And I found out that it can only work when i comment out the #include"io.h"
    Appreciated you kind help!

    • nascardriver

      Please use code tags when posting code. Whenever you get an error, post the full error message.
      You're already including "io.h" at the top of "main.cpp", you don't need to include it again at the end. Although that's not good, it shouldn't cause an error.

    • NEERAJ

      You have not defined/initialed z anywhere and not set sum = z either

      • 3LI M 3alim

        @NEERAJ sum is defined as a local variable.Also z is a parameter of the function, to show this function expects an input.So no need to set sum = z.this code should wrok fine

  • Zim

    How come it won't compile unless I have #include <iostream> in both .CPP files.I get the court undeclared identifyer.

    • nascardriver

      All files that use `std::cout` have to #include <iostream>. Since you didn't post your code, I'm assuming that you're using `std::cout` in main.cpp.

  • Renga

    The above compile just fine ,but I'm not sure is this right.
    Please help
    thank you.

  • ElloMate

    Hi, thanks for the content. This is the code I have for questions 1.

    #include <iostream>

    int readNumber()
    {
        std::cout << "Enter a number: " ;
        int x;
        std::cin >> x;

        std::cout << "Enter another number: " ;
        int y;
        std::cin >> y;

        return x + y;
    }

    void writeAnswer()
    {
        std::cout <<"The sum of the two numbers is: " << readNumber();
        
    }

    int main()
    {
        std::cout << writeAnswer();

        return 0;
    }

    I realize this does not follow the questions exactly but if someone could explain why I'm getting an error in line 32 saying:

    binary '<<': no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)    

    it would be appreciated. Also the code runs but when I enter 10 and 10 I get an output of 200. Any thoughts? I realize these may be very basic questions but any help would be great. Thank you!

  • In question #1, my code was very similar (except the main() part,where i needed to check the solution). The problem is that the program runs, but only compiles upto readNumber().
    It just continuously says "enter a number". I can't find the problem.

    • nascardriver

      There's nothing wrong with your code. Your issue sounds like you're using an online IDE without support for user input.

  • sami

    Hi,
    I don't get it why you #include "io.h" in io.cpp? I read the comment and it is still confusing :(

    • nascardriver

      We explained this in lesson 2.11, section "Including a header in the corresponding source file". If you don't understand it, keep reading the tutorials and look back at it later. Chances are it makes more sense when you've seen more of the language.

  • sami

    "When two identifiers are introduced into the same program in a way that the compiler can’t tell them apart, the compiler or linker will produce a naming collision."

    Shouldn't the sentence above rewrite as the following:

    "When two identifiers are introduced into the same program in a way that they can’t be distinguished, the compiler or linker will produce a naming collision."

    When you said "the compiler can't tell them apart, it implies that even the moment when linker produces a naming collision, it is because still the compiler can't tell them apart.

  • Satla

    Hi,

    I am compiling in VS code. I am getting below error

    C:\Users\satla\AppData\Local\Temp\ccFAG5YC.o:main.cpp:(.text+0xf): undefined reference to `readNumber()'
    C:\Users\satla\AppData\Local\Temp\ccFAG5YC.o:main.cpp:(.text+0x18): undefined reference to `readNumber()'
    C:\Users\satla\AppData\Local\Temp\ccFAG5YC.o:main.cpp:(.text+0x2e): undefined reference to `writeAnswer(int)'
    collect2.exe: error: ld returned 1 exit status

    Even If I try with the same code as your, same error is seen.

    Can you please help me with it?

    Thanks

    • nascardriver

      You're not compiling "io.cpp", only "main.cpp". I can't tell you what you did wrong, look up instructions on how to add a source file in VS.

  • Gabe

    main.cpp

    io.cpp

    io.h

  • ColdCoffee

    Your solution of question 1 gives following error:

    1>------ Build started: Project: addition, Configuration: Debug Win32 ------
    1>LINK : C:\Users\DELL\source\repos\addition\Debug\addition.exe not found or not built by the last incremental link; performing full link
    1>addition.vcxproj -> C:\Users\DELL\source\repos\addition\Debug\addition.exe
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

  • Hello!
    In question-3 io.cpp, why do we have to include io.h?
                      It doesn't need forward declarations.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]