learn cpp(C++) Chap 2

Ace your homework & exams now with Quizwiz!

What does the abbreviation DRY mean?

"Don't Repeat Yourself" (often abbreviated "DRY")

How can you make a program do a "functions calling functions calling functions"?

#include <iostream> // for std::cout void doB() { std::cout << "In doB()\n"; } void doA() { std::cout << "Starting doA()\n"; doB(); std::cout << "Ending doA()\n"; } // Definition of function main() int main() { std::cout << "Starting main()\n"; doA(); std::cout << "Ending main()\n"; return 0; }

Here are some preprocessor directives>>

#include<iostream>(When the preprocessor runs on this program, the preprocessor will replace #include <iostream> with the preprocessed contents of the file named "iostream".),#define,

defining local variables

Local variables inside the function body should be defined as close to their first use as reasonable:

lifetime

Much like a person's lifetime is defined to be the time between their birth and death, an object's lifetime is defined to be the time between its creation and destruction.

key insight 1

Names used for function parameters or variables declared in a function body are only visible within the function that declares them. This means local variables within a function can be named without regard for the names of variables in other functions. This helps keep functions independent.

nested functions?

Nested functions are not allowed.

Can you nest functions in C++?

No. Unlike some other programming languages, in C++, functions cannot be defined inside other functions.

Goal of a header guard

Note that the goal of header guards is to prevent a code file from receiving more than one copy of a guarded header. By design, header guards do not prevent a given header file from being included (once) into separate code files. This can also cause unexpected problems. Consider:

multi-file compile errors

Remember, the compiler compiles each file individually.It does not know about the contents of other code files, or remember anything it has seen from previously compiled code files. So even though the compiler may have seen the definition of function add previously (if it compiled add.cpp first), it doesn't remember.

whats a macro

The #define directive can be used to create a macro. In C++, a macro is a rule that defines how input text is converted into replacement output text.

scope resolution operator

The :: symbol is an operator called the scope resolution operator.

Function body

The curly braces and statements in a user defined function.

why use functions?

Use functions for organization, reusability, testing, extensibility, abstraction

How do parameters and arguments work together(pass by value)

When a function is called, all of the parameters of the function are created as variables, and the value of each of the arguments is copied into the matching parameter. This process is called pass by value.

New programming tip

When addressing compile errors in your programs, always resolve the first error produced first and then compile again.

Do you need to include parenthesis () after the function's name when making a function call?

Yes.

naming collision

all identifiers be non-ambiguous. If two identical 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 an error. This error is generally referred to as a naming collision (or naming conflict).

#ifdef preprocessor directive

allows the preprocessor to check whether an identifier has been previously #defined. If so, the code between the #ifdef and matching #endif is compiled. If not, the code is ignored.

What happens during translation

https://en.cppreference.com/w/cpp/language/translation_phases

A code file with translations applied to it is called a...?

translation unit

refactoring

when you split a complicated/long function into two sub-functions

Most naming collisions occur in two cases:

1) Two (or more) definitions for a function (or global variable) are introduced into separate files that are compiled into the same program. This will result in a linker error, as shown above.2) Two (or more) definitions for a function (or global variable) are introduced into the same file (often via an #include). This will result in a compiler error.

when learning c++ you'll write a lot of programs that involve 3 subtask

1.Reading inputs from the user 2.Calculating a value from the inputs 3.Printing the calculated value

namespace

A namespace is a region that allows you to declare names inside of it for the purpose of disambiguation. The namespace provides a scope (called namespace scope) to the names declared inside of it -- which simply means that any name declared inside the namespace won't be mistaken for identical names in other scopes.

using directive

A using directive tells the compiler to check a specified namespace when trying to resolve an identifier that has no namespace prefix. So in the above example, when the compiler goes to determine what identifier cout is, it will check both locally (where it is undefined) and in the std namespace (where it will match to std::cout).

header guard

All of your header files should have header guards on them. SOME_UNIQUE_NAME_HERE can be any name you want, but by convention is set to the full filename of the header file, typed in all caps, using underscores for spaces or punctuation. For example, square.h would have the header guard:

an argument

An argument is a value that is passed from the caller to the function when a function call is made:

What status code means a program executed successfully?

By definition, a status code of 0 means the program executed successfully.

what is return type?

First, your function has to indicate what type of value will be returned. This is done by setting the function's return type, which is the type that is defined before the function's name.

"Can't we just put all the code inside the main function?"

For simple programs, you absolutely can.

how to use function parameters

Function parameters are defined in the function declaration by placing them in between the parenthesis after the function identifier, with multiple parameters being separated by commas.

local variables

Function parameters, as well as variables defined inside the function body, are called local variables

What does a function like macro do?

Function-like macros act like functions, and serve a similar purpose. We will not discuss them here, because their use is generally considered dangerous, and almost anything they can do can be done by a normal function.

user-defined functions

Functions that you write yourself are called...?

scope is a compile time property meaning?

Scope is a compile-time property, and trying to use an identifier when it is not in scope will result in a compile error.

What is this: return-type identifier() // identifier replaced with the name of your function { // Your code here }

This is an example of a user identified function. The identifier is the name of the user-defined function, the parenthesis tell the compiler that we're defining that as a function, the curly braces and statements in between are called the function body.

why use multi-files in programs

This limited visibility and short memory is intentional, so that files may have functions or variables that have the same names without conflicting with each other.

Why use a void return value?

To tell compiler that the function does not return a value, you use void return.

Object-like macros with substitution text

When the preprocessor encounters this directive, any further occurrence of the identifier is replaced by substitution_text. The identifier is traditionally typed in all capital letters, using underscores to represent spaces.

return by value?

When the return statement is executed, the return value is copied from the function back to the caller. This process is called return by value.

#include

When you #include a file, the content of the included file is inserted at the point of inclusion. This provides a useful way to pull in declarations from another file.

When you use an identifier that is defined inside a namespace...

When you use an identifier that is defined inside a namespace (such as the std namespace), you have to tell the compiler that the identifier lives inside the namespace. Explicit namespace qualifier std:: So when we say std::cout, we're saying "the cout that lives in namespace std".

Return values

When you write a user-defined function, you get to determine whether your function will return a value back to the caller or not. To return a value back to the caller, two things are needed.

all declarations are not definitions, true or false?

While it is true that all definitions are declarations, the converse is not true: all declarations are not definitions.

pure declarations

declarations that aren't definitions are called pure declarations.

#ifndef

is the opposite of #ifdef, in that it allows you to check whether an identifier has NOT been #defined yet.

are using directives and preprocessor directives the same?

no. So while the term directive usually means a preprocessor directive, this is not always the case.

function calls in order?

no. The C++ specification does not define whether function calls evaluate arguments left to right or right to left. Take care not to make function calls where argument order matters.

What are the two basic types of macros?

object-like macros, and function-like macros.

header files should not contain..?

Header files should generally not contain function and variable definitions, so as not to violate the one definition rule. An exception is made for symbolic constants (which we cover in lesson 4.14 -- Const, constexpr, and symbolic constants).

errors in multi-file and how to fix

If you get a compiler error about add not being defined in main, you probably forgot the forward declaration for function add in main.cpp. 2. If you get a linker error about add not being defined, e.g.3. Do not #include "add.cpp" from main.cpp. This will cause the compiler to insert the contents of add.cpp directly into main.cpp instead of treating them as separate files.

How to call functions more than once?

Like this for example: Starting main() In doPrint() In doPrint() Ending main() Since doPrint gets called twice by main, doPrint executes twice, and In doPrint() gets printed twice (once for each call).

lifetime run property

Note that variable creation and destruction happen when the program is running (called runtime), not at compile time. Therefore, lifetime is a runtime property.

What are object like macros?

Object-like macros can be defined in one of two ways: #define identifier #define identifier substitution_text The top definition has no substitution text, whereas the bottom one does. Because these are preprocessor directives (not statements), note that neither form ends with a semicolon. Object-like macros should only be seen in legacy code anymore.Object-like macros don't affect other preprocessor directives(so they don't cancel eachother out they only cancel out other code).

#if 0

One more common use of conditional compilation involves using #if 0 to exclude a block of code from being compiled (as if it were inside a comment block):

return value?

The specific value returned from a function is called the return value.

Best practice to maximize the chance that missing includes will be flagged...

Best practice To maximize the chance that missing includes will be flagged by compiler, order your #includes as follows: The paired header file Other headers from your project 3rd party library headers Standard library headers The headers for each grouping should be sorted alphabetically.

global namespace

In C++, any name that is not defined inside a class, function, or a namespace is considered to be part of an implicitly defined namespace called the global namespace (sometimes also called the global scope).

#pragma once

#pragma once serves the same purpose as header guards, and has the added benefit of being shorter and less error-prone. However, #pragma once is not an official part of the C++ language, and not all compilers support it (although most modern compilers do). For compatibility purposes, we recommend sticking to traditional header guards. They aren't much more work and they're guaranteed to be supported on all compliant compilers.

argument and initializer

(as the argument is essentially just an initializer for the parameter, and initializers can be any valid expression).

one definition rule (or ODR for short) is a well-known rule in C++

1.Within a given file, a function, object, type, or template can only have one definition. 2.Within a given program, an object or normal function can only have one definition. This distinction is made because programs can have more than one file (we'll cover this in the next lesson). 3.Types, templates, inline functions, and variables are allowed to have identical definitions in different files. We haven't covered what most of these things are yet, so don't worry about this for now -- we'll bring it back up when it's relevant.

scope

An identifier's scope determines where the identifier can be accessed within the source code. When an identifier can be accessed, we say it is in scope.When an identifier can not be accessed, we say it is out of scope.

bestpractice header file

As previously mentioned, manually adding forward declarations for every function you want to use that lives in another file can get tedious quickly. Let's write a header file to relieve us of this burden. Writing a header file is surprisingly easy, as header files only consist of two parts: A header guard, which we'll discuss in more detail in the next lesson (2.11 -- Header guards). The actual content of the header file, which should be the forward declarations for all of the identifiers we want other files to be able to see.

paraments and return values together do what?

By using both parameters and a return value, we can create functions that take data as input, do some calculation with it, and return the value to the caller.

Header file

C++ code files (with a .cpp extension) are not the only files commonly seen in C++ programs. The other type of file is called a header file. .hpp extension

The scope of defines

Directives are resolved before compilation, from top to bottom on a file-by-file basis.For general readability, you'll generally want to #define identifiers outside of functions. Once the preprocessor has finished, all defined identifiers from that file are discarded. This means that directives are only valid from the point of definition to the end of the file in which they are defined. Directives defined in one code file do not have impact on other code files in the same project.

what does a header file do

Header files usually have a .h extension, but you will occasionally see them with a .hpp extension or no extension at all. The primary purpose of a header file is to propagate declarations to code files.

header file pairing best practice

If a header file is paired with a code file (e.g. add.h with add.cpp), they should both have the same base name (add). Source files should include their paired header. Because something.cpp #includes something.h, the compiler will notice that function something() has a mismatched return type and give us a compile error. If something.cpp did not #include something.h, we'd have to wait until the linker discovered the discrepancy, which wastes time. For another example, see this comment.

Why is repeated code bad?

If we wanted to change the text "Enter an integer:" to something else, we'd have to update it in two locations. And what if we wanted to initialize 10 variables instead of 2? That would be a lot of redundant code (making our programs longer and harder to understand), and a lot of room for typos to creep in.

The #include order of header files

If your header files are written properly and #include everything they need, the order of inclusion shouldn't matter. Now consider the following scenario: let's say header A needs declarations from header B, but forgets to include it. In our code file, if we include header B before header A, our code will still compile! This is because the compiler will compile all the declarations from B before it compiles the code from A that depends on those declarations. However, if we include header A first, then the compiler will complain because the code from A will be compiled before the compiler has seen the declarations from B. This is actually preferable, because the error has been surfaced, and we can then fix it.

pass info to a function being called

In many cases, it is useful to be able to pass information to a function being called, so that the function has data to work with. For example, if we wanted to write a function to add two numbers, we need some way to tell the function which two numbers to add when we call it. Otherwise, how would the function know what to add? We do that via function parameters and arguments.

New programmer mistake to be aware of

New programmers often combine calculating a value and printing the calculated value into a single function. However, this violates the "one task" rule of thumb for functions. A function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value (such as call another function to print the value).

return statement (2)

Second, inside the function that will return a value, we use a return statement to indicate the specific value being returned to the caller.

Conditional compilation

The conditional compilation preprocessor directives allow you to specify under what conditions something will or won't compile. There are quite a few different conditional compilation directives, but we'll only cover the three that are used by far the most here: #ifdef, #ifndef, and #endif.

Caller function

The function initiating the function call

what exactly is a function prototype?

The function prototype consists of the function's return type, name, parameters, but no function body (the curly braces and everything in between them), terminated with a semicolon. example: int add(int x, int y);

Callee or called function

The function that is being called by the caller function is called the callee or called function

We've generally told you not to include function definitions in your headers. So you may be wondering why you should include header guards if they protect you from something you shouldn't do.

There are quite a few cases we'll show you in the future where it's necessary to put non-function definitions in a header file. For example, C++ will let you create your own types. These user-defined types are typically defined in header files, so the definition can be propagated out to the code files that need to use them. Without a header guard, your code files can end up with multiple identical copies of these definitions, which will cause a duplicate definition compilation error.

What's a function prototype used for?

To write a forward declaration for a function, we use a declaration statement called a function prototype.

Object-like macros without substitution text

Unlike object-like macros with substitution text, macros of this form are generally considered acceptable to use.

double quotes to include header files

Use double quotes to include header files that you've written or are expected to be found in the current directory. Use angled brackets to include headers that come with your compiler, OS, or third-party libraries you've installed elsewhere on your system.

How to give files access to functions that live in another file?

Use foward declarations. example: Now, when the compiler is compiling main.cpp, it will know what identifier add is and be satisfied. The linker will connect the function call to add in main.cpp to the definition of function add in add.cpp.

Translation

When you compile your code, you might expect that the compiler compiles the code exactly as you've written it. This actually isn't the case. Prior to compilation, the code file goes through a phase known as translation.

Does the compiler compiles the contents of code files sequentially?

Yes so identify your functions and variables

Should you always explicitly provide a return value for any function that has a non-void return type?

Yes. It is best practice to do so.

declaration

a statement that tells the compiler about the existence of an identifier and its type information.

whats function parameter

a variable used in a function. Function parameters work almost identically to variables defined inside the function, but with one difference: they are always initialized with a value provided by the caller of the function.

a definition

actually implements (for functions or types) or instantiates (for variables) the identifier.

A forward declaration

allows us to tell the compiler about the existence of an identifier before actually defining the identifier.

A function call

an expression that tells the CPU to interrupt the current function and execute another function. The CPU "puts a bookmark" at the current point of execution, and then calls (executes) the function named in the function call.

Preprocessor directives (often just called directives)

are instructions that start with a # symbol and end with a newline (NOT a semicolon). These directives tell the preprocessor to perform specific particular text manipulation tasks. Note that the preprocessor does not understand C++ syntax -- instead, the directives have their own syntax (which in some cases resembles C++ syntax, and in other cases, not so much).

Warning/discourage of using a using directive , such as using namespace std;//makes std::cout accessible as "cout"

because the compiler now can't tell whether we want the cout function that we defined, or the cout that is defined inside the std namespace. ven worse, while an identifier name may not conflict today, it may conflict with new identifiers added to the std namespace in future language revisions. This was the whole point of moving all of the identifiers in the standard library into the std namespace in the first place!

preprocessor

best thought of as a separate program that manipulates the text in each code file. When the preprocessor runs, it scans through the code file (from top to bottom), looking for preprocessor directives.

The return value from main is sometimes called a...?

status code

Modular programming

the ability to write a function, test it, ensure that it works, and then know that we can reuse it as many times as we want and it will continue to work (so long as we don't modify the function -- at which point we'll have to retest it). Best practice


Related study sets

"A New Oceania: Our Sea of Islands" by Epeli Hauʻofa

View Set

MyProgrammingLab Starting out with python ch.4

View Set

Chapter 12 Classification of Neurons

View Set

Movement Anatomy (role of agonist muscles, Stabilizer Muscles, Synergist Muscles) Q2

View Set

Module 8 Unit 4: Economic Theory and Fiscal Policy

View Set

StraighterLine Intro to Communication: Exam Q&As

View Set

A&P Mastery Unit 1 Ch 1 Practice Q 1

View Set

Read works Where Does Your Food Come From?

View Set

ch 1 completing the application, underwriting, and delivering the policy

View Set