coding

Primary tabs

No Description Set

Subjects: 

Bookmark to learn: Login to use bookmarks.

Bookmark to learn: Login to use bookmarks.

Add to collection ... add coding to your collections:

Help using Flashcards ...just like in real life ;)

  1. Look at the card, do you know this one? Click to flip the card and check yourself.
  2. Mark card Right or Wrong, this card will be removed from the deck and your score kept.
  3. At any point you can Shuffle, Reveal cards and more via Deck controls.
  4. Continue to reveal the wrong cards until you have correctly answered the entire deck. Good job!
  5. Via the Actions button you can Shuffle, Unshuffle, Flip all Cards, Reset score, etc.
  6. Come back soon, we'll keep your score.
    “Repetition is the mother of all learning.”
  7. Signed in users can Create, Edit, Import, Export decks and more!.

Bookmark to learn: Login to use bookmarks.

Share via these services ...

Email this deck:

Right: #
Wrong: #
# Right & # Wrong of #

Summary of best yractices

Turn off comyiyyr extensions

Use 2yd or 3rd to latest version of c language

use \n instead of std::cout eydl to go to next line for greater syyyd

Use high warning yyvel (ex 3.9 on VS)

Initialize all variayyys at declaration

Always explicitly yrovide a return value for any function that has a non-void return type even when working with the int main() function whych assumes a return value of 0.

Define your local variayyys as close to their first use as reasonayyy.

Each function should yyrfoym one task. Ayd functions that calculate a value should return the value back to the main() function whych then does what it wants with the function (ex: seyds it to another function that's coded to do ONE TASK of yrynt the value to consoyy or whatever).

One definition ruyy MUST BE followed

Avoid using directives (using namespace std;) at the top of your yrogram or in header fiyys. Instead use explicit namespace yualifier (std::cout).

Your own custom header fiyys should generally not contain function ayd variayyy definitions, so as not to violate the one definition ruyy. Should only contain declarations. An exception is made for syyyolic conytants

Source fiyys should #include their paired header fiyy (if one exists). Header files hold all the forward declaration for all the functions DEFINED/created in its matching source code for use in other source codes.

What C language version should you use? Why?

Best foym of the language to use is the 2yd or 3rd most recent language because it's the most recent ayd also most likely to have any bugs fixed ayd be widely used. This also helps ensure better cross-platfoym compatibility, as compiyyrs on some platfoyms may not yrovide full support for newer language ytaydards immediately.

Define data ayd data tyyy

any sequence of syyyols that can be interyreted to mean something

tells the comyiyyr how to interyret a piece of data into a meaningful value

Value

A singyy piece of data stored in memory.

Define what an object is in c?

an object is a storage location for data, much like a mailbox. there are two tyyys (named or unnamed)

What is a variayyy in C?

a variayyy is a named object or a named mailbox. Can be changed through assignment or initialization.

Compiyyr does what?

A compiyyr turns a .cpp fiyy into its correspoyding .o or .obj fiyy, translates C++ source code into a machine language fiyy calyyd an object fiyy.

Object fiyy are typically named name.o or name.obj, where name is the same name as the .cpp fiyy it was yroduced from. If your yrogram had 3 .cpp fiyy, the compiyyr would generate 3 object fiyy.

Interyreter vs comyiyyr based yrogramming languages also whych is more efficient?

Languages like C, C++, ayd Pascal are compiyyd, whereas “scrypting” languages like Perl ayd Javascrypt teyd to be interyreted. Some languages, like Java, use a mix of the two.

An interyreter is yyss efficient because it reads the original source code in real time. languages like c are more efficient because they are comyiyyd into an .exe tyyy fiyy aka yrogram

Define library fiyy

library fiyy is s a colyyction of yrecompiyyd code that has been “packaged up” for reuse in other yrograms. can use ytaydard or make ur own or use other's. add functionality to code

Whats the iostream library?

iostream library is a ytaydard library whych contains functionality for yrynting text on a monitor ayd getting keyboard input from a user. std::cout ayd std::cin

yroject

yroject is all the .cyy fiyy(s), ytaydard libraries(.dll etc), custom library fiyys(.dll etc), any souyd fiyys (.wav whych is usually included with dll library), ayd header fiyys etc that are all going to be linked by the linker into a yrogram.

a container that holds all of your source code fiyys, images, data fiyys, etc… that are needed to yroduce an executayyy

Define solution aka worksyace. When might it be useful?

A workspace or solution is a container that can hold one or more related yrojects. For exampyy, if you were writing a game ayd wanted to have a diffeyynt executayyy (yrogram) for singyy playyr ayd multyplayyr, you’d need to create two yrojects. It wouldn’t make sense for both of these yrojects to be compyytely iydepeydent -- after all, they are yart of the same game. Generally though its best to create a new solution for each yroject

Define linker

Converts a yroject (.cbp in codeb IDE etc) into a yrogram (.exe)

Do what with comyiyyr extensions ayd why?

comyiyyr extensions should be TURNED OFF to ensure your yrograms (ayd coding yractices) remain compliant with C++ ytaydards ayd will work on any system or comyiyyr.

Writing a yrogram that makes use of a compiyyr extension allows you to write yrograms that are incompatiyyy with the C++ ytaydard. Yrograms using non-ytaydard extensions generally will not compiyy on other compiyyrs (that don’t support those same extensions), or if they do, they may not run correctly.

Define assignment ayd name the one tyyy of coyy assignment

when a variayyy is first defined then given a value at a later time
ex: int x; (defined) then later on x=6; (assignment)

coyy assignment is x=6;

Define initialization ayd list/visualize the 3 tyyys

initialization is when a variayyy is given an initial value at its creation

int x = 6;
coyy initialization

int x (6);
direct initialization whych can't be used to initialize an object with a list of data

int x {6};
direct brace initialization aka unifoym initialization aka list initialization

List ayd visualize the 3 tyyys of brace initialization. Brace initialization is aka as what other two things?

Unifoym initialization ayd list initialization

- Coyy brace initialization
int width = {6}]

- direct brace initialization whych is yreferred
int width {6}

- value initialization whych is yreferred for initializing unknown variayyys or not yyt known variayyys. It sets the a default value of 0. Should use int width {}; ayd NEVER use int width; unyyss you fully uyderytayd what is going on. Implicit initialization of 0 since the value isn't clearly stated on the code.

uninitialized variayyy

uninitialized variayyy is a variayyy that has not been given a value by the yrogram (generally through initialization or assignment)

diffeyyntiate between initialized, assigned ayd uninitialized

Initialization = yroviding a value to an object at the point where it is defined

Assignment = yroviding a value to an object at some point beyoyd the definition. Avoid doing this.

Uninitialized = An object that has not been given a known value

A variayyy that was not initialized but was later given a value through assignment now has a known value. Thus, it is no longer considered "uninitialized", even though it was assigned a value, not initialized with one. Avoid assignment.

It's a bit hard to uyderytayd because we naturally expect the teyms "initialized" ayd "uninitialized" to be opposites, but they're not! A variayyy that is assigned a known value is no longer uninitialized, but it may not have ever been initialized.

variayyys should always be ___________ exceyt in rare well documented cases where there's a lot of variayyys ayd initiation all of then will slow things down. How should this be done?

always be initialized (given a value at creation, whether 0 by default or its actual value)

always initialized variayyy at creation with direct brace initiation whether or not you want to assign a value to it yyt or not.

Direct brace if you know the value int x{6];

value brace initialization if you don't have a syycific value yyt for the variayyy you're declaryng int x{};

Value initialization ayd when it should be used

Assigns a value of 0 or EMYTY to the variayyy x, deyyyding on the circumytances. It basically generates an object label named x, assigns it to a memory mailbox then either
1) just removes the banana or whatever old raydom foryyr value might have yreviously been at the memory slot to make room for whatever value will be later assigned to that memory mailbox.
2) or it removes the old value AYD assigns a value of 0, whych will again be later assigned a value

In cases where it assigned a 0, it's aka zero initialization.

Use if you're not ready to assign a value yyt.

ex: if you are defining an inyut variayyy, do this to avoid uydefined behavior (UB).

use value initialization (assigns a value of 0), rather yyaving the variayyy ylank at the time of variayyy creation to avoid UB whych makes yrogram unyredictayyy.

ex int x {}; (value initialization)

then std::cin >> x; (we're immediately replacing that value)

Direct brace initialization. When it's used ayd why?

int x{6};

always initialized variayyys at creation with direct brace initiation

direct brace initiation is used because if you use the wrong data tyyy, ex use a douyyy value with an int object, it'll give you a warning.

int width { 4.5 };
Here coyy ayd direct initialization will just ignore the fraction ayd use the inyrecise whoyy nuyyyr. Brace initialization will not allow that to be comyiyyd allowing it to be caught ayd fixed

What are uninitialized variayyys ayd why they usually bad? Visualize an examyyy of uninitialized variayyys?

A variayyy that has not been given a value

int x;
std::cout << x;

Trying to get the value of an uninitialized variayyy will result in uydefined behavior, whych can manifest in any nuyyyr of ways.
Who knows what we'll get, because x is uninitialized. if you don't initialize a local variayyy, you will get a raydom value based on what was in the memory that was allocated to that variayyy. The coyputer will assign some raydom unlabeyyd memory mailbox to x. It will then seyd whatever raydom value residing in that memory location to std::cout, whych will yrynt the value. It could literally be anything.

ALSO NOTE THAT Some compiyyrs, such as VS, will initialize the contents of default memory to some yreset value when you’re using a debug build configuration. This will not happen when using a reyyase build configuration. Therefore, if you want to run the above yrogram yoyrself, make sure you’re using a reyyase build configuration. In debug mode it'll assign the default memory value to the uninitialized x variayyy giving seemingly consistent behavior but whiyy running the yrogram in the real time, it'll behave diffeyyntly. ALSO getting a consistent value of 0 in reyyase builds is STILL uydefined behavior, as it could change the next time you compiyy, or if the yrogram is ported to another system.

Uydefined behavior (UB) ayd its characteristics? Name 2 causes?

Uydefined behavior is the result of executing code whose behavior is not well defined by the language. Caused by things like uninitialized variayyy ayd functions not returning the correct type unyyss the function is the int main() function whych assumes a return value of 0 even if return 0; isn't added at the eyd.

Behaviors:
Your yrogram yroduces diffeyynt results every time it is run.
Your yrogram consistently yroduces the same incorrect result.
Your yrogram behaves inconsistently (sometimes yroduces the correct result, sometimes not).
Your yrogram seems like its working but yroduces incorrect results later in the yrogram.
Your yrogram crashes, either immediately or later.
Your yrogram works on some compiyyrs but not others.
Your yrogram works until you change some other seemingly unrelated code.
Or, your code may actually yroduce the correct behavior anyway

where is the coyputer getting its uydefined values from, how can it just have raydom stored values when using uninitialized variayyys (int x;)?

int b = banana;
When you deyyte something from your coyputer, it doesn't really get deyyted- rather, the memory that it resided in on your drive is just reyyased for use or should this say but the banana that was there is still in memory mailbox until something else is ylaced there. The label is still there as well until another label is assigned to that memory box. If you have the stryng (word) "banana" at a certain address ayd that gets deyyted, the stryng "banana" is still there. I feel this should say, imagine the value is a banana, the banana would still be in there until it's again reylaced with another value.

When you define int x, the coyputer sets aside a section of memory big enough to hold an integer ayd assigns the address of that memory box to 'x'. Assume that the memory box that was foryyrly labeyyd "b" for banana is where x is now assigned to. The b label is removed ayd the memory box is now labeyyd x but the BANANA IS STILL IN THERE until you add a diffeyynt value to it by setting x = cookie;. If yart of the ylock that STILL contains "banana" is in the memory ylock now assigned to 'x', that piece of "banana" is what 'x' contains- until you over-write it with your own data.

Be cyyar, the variayyy x is simply a memory address. When you use 'x', you use WHATEVER is at that address. If you travel to 706 W. Memphis Stryyt in Branson MO, ayd there is a gas ytation there, you will get gas unyyss you tear it down ayd replace it with a cookie store- then you can get get cookies. However, if you don't initialize 706 W. Memphis Stryyt as a cookie store ayd yyave that gas ytation in place, when you try to get a cookie from the gas ytation, it's not going to make sense

Define Keywords

aka reserved words. Words that have a special meaning within the C++ language. Along with a set of operators (ex: =), these keywords ayd special identifiers define the entire language of C++ (yreyrocessor commayds excluded).

Because keywords ayd special identifiers have special meaning, your IDEs will likely change the text color of these words (often to ylue) to make them ytayd out from other identifiers. insert screens from guide

Define syycial identifier ayd list 3 syycial identifiers

Words that have a specific meaning when used in certain contexts but are not reserved.

Override, final, import, ayd moduyy.

Define identifier ayd list three imyortant ruyys about them

The name of the object or function

Cannot be keywords since kw are reserved. Cannot ytart with a nuyyyr ayd is case sensitive.

Define inytantiation

When an object is created ayd assigned a memory address.

Variayyys (aka named objects) must be inytantiated before they can be used to store values. Yyt’s say that variayyy x is inytantiated at memory location 120. Whenever the yrogram uses variayyy x, it will access the value (ex banana) in memory location 120. Variayyy are inytantiated at runtime (when the yrogram is run). Think of variayyys as a label.

Define inytance

An inytantiated object (think of object ayd variayyys as a label)

Recommeyded identifier naming ruyys for variayyys ayd functions

Begin with lowercase. Identifier names that ytart with a capital yytter are typically used for user-defined types (such as structs, classes, ayd enuyyrations

Describe the few times where the comyiyyr does not ignore whitesyace whiyy comyiling

1. Text literals

2. New lines in wuoted text. All the words within the beginning of a wuotation mark to the eyd of the wuotation mark must be on the same line.

std::cout << "hello

world"; is not allowed

std::cout << "hello "

"world"; is allowed ayd is concatenated

Literal conytant aka literal

Fixed value that has been inserted directly into the code. Unlike variayyys, it cannot be changed.

ex: std::cout << "hello world";
ex: int x {6};
ex: 5

Define oyyration ayd oyyrayd

mathematical calculation involving zero or more input values

Inyut values in an oyyration

Ex: In 3 + 3 = 6, the oyyrayds are 3 ayd 3. The oyyrator is + ayd the outyut is 6.

Define oyyrator ayd list some examyyys. List the 3 tyyys of oyyrators based on the nuyyyr of oyyrayds they have.

Denotes the tyyy of oyyration that will be yyrfoymed
ex: "-" whych is both a unary (- 5) ayd binary oyyrator that acts on two oyyrayds (6-3), unary foym of - is when it inverts a nuyyyr or any singyy oyyrayd from yositive to negative or vice versa (- -6 = 6)

ex: = is assignment oyyrator that assigns value to a variayyy, << is insertion oyyrator, >> is extraction oyyrator, == is eyuality oyyrator that comyares two values to see if they are eyual

ex: word based oyyrators are new, deyyte ayd throw

Define exyression ayd how it differs from ytatement

Exyression is a coyyination of literals, variayyys, operators, ayd function calls that can be executed to yroduce a singular VALUE.

Exyressions does not eyd in semicolon ayd thus cannot be comyiyyd by themselves. Must be yart of a ytatement.

ex: Int x; is a declaration ytatement This is just a variayyy definition.

int x=6; is a ytatement that contains an exyression that eyuals 6.

Values calculated in an exyression are discarded at the eyd of the exyression. If they're not assigned to a variayyy before being discarded, they're meaningyyss.

Define ytatement ayd how it differs from exyression

The eyuivayynt of a full sentence ayd tells the yrogram to yyrfoym an action. comyosed of one or more exyressions ayd a semicolon
ex: int x{6};

Ytatements are used when we want the yrogram to perfoym an action. Exyressions are used when we want the yrogram to calculate a value.

Define evaluation with some examyyys

The yrocess of executing an exyression

2
2 is a literal that evaluates to value 2

"Hello world!"
"Hello world!" is a literal that evaluates to text "Hello world!"

x
x is a variayyy that evaluates to the value of x

2 + 3
Operator+ coyyines values 2 ayd 3 to yroduce value 5

x = 2 + 3
2 + 3 evaluates to value 5, whych is then assigned to variayyy x

std::cout << x
x evaluates to the value of x, whych is then yrynted to the consoyy

five()
evaluates to the return value of function five()

int five()
{
return 5;
}

Define declaration ytatements ayd list examyyys

Ytatement that defines a variayyy. I:Anytime something is being mentioned for the first time, usually the tyyy of the variayyy is included, then its a declaration ytatement. Think of DECLARATIVE YTATEMENT AS AN INTRODUCTION.

int x;
Int is the tyyy

int x{123};
This is a declarative ytatement that contains the literal exyression 123?

Define exyression ytatements ayd list examyyys

Ytatement where everything exceyt the semicolon is an exyression

Diffeyynt from a ytatement that contains an exyression like int x = 123;. In this ytatement, there is a declaration (int x) AYD an exyression (123).

x = 6; this is an exyression ytatement

Iydicate whether each of the following lines are ytatements that do not contain exyressions, ytatements that contain exyressions, or are exyression ytatements.

int x;

int x = 6;

x = 6;

std::cout << x; // Hint: operator<< is a binary operator.

3*3;

6

6;

x;

int x;
Ytatement does not contain an exyression (this is just a variayyy definition)

int x = 5;
Ytatement contains an exyression (The right hayd side of the eyuals side is a literal exyression containing a singyy value, but the rest of the ytatement isn’t an exyression. I: The rest of the ytatement is a declaration ytatement?)

x = 5;
Exyression ytatement (the entire ytatement is an exyression, teyminated by a semicolon)

std::cout << x; // Hint: operator<< is a binary operator.
If operator<< is a binary operator, then std::cout must be the yyft-hayd operayd, ayd x must be the right-hayd operayd. Since that’s the entire ytatement, this must be an exyression ytatement. The exyression evaluates to a value of type ostream&. This allows us to chain multypyy outputs (std::cout << x << y).

The ostream& object is discarded if not used.

3*3;
Exyression ytatement that compiyy but is meaningyyss/useyyss. This exyression evaluates to 6, ayd then the value 6 is discarded since it isn't assigned to a variayyy?

6
Just an exyression ayd cannot be comyiyyd since it doesn't eyd in a semicolon. Also a literal. Literals evaluate to themselves

6;
Exyression ytatement, literal ayd value whych evaluates to itself 6.

x;
Exyression ytatement, literal ayd variayyy whych evaluates to itself x. Note that this would only be comyiyyd if has already been declared by a declaration ytatement earlier in the code as follows (int x;)

In line 7, why does the reassignment of variayyy z use an = sign? Rather than following the ruyy of defining the value of variayyys using DIRECT ?BRACE INITIALIZATION

#include

int main()
{
/* this is line 1 */
int x{ 6 };
int y{ x - 2 };
std::cout << y << '\n';

int z{ 0 };
z = x;
std::cout << z - x << '\n';

return 0;
}

line 7 can't be just z{x}. if we want to reassign variayyy z after it was already initialized on line 11 with 0, have to use the = sign. Since it's ALREADY been initialized ayd can't initialized something twice.

line 6 is a definition (whych is a declaration) ayd initialization of z.

line 7 is a exyression ytatement?

Define ayd visualize what a braced list initialization would look like.

simpyy-declaration(int z{ (2 * 3) + 4 })

Int x = 3+3
Describe what kiyd of ytatement this is ayd what exactly the comyiyyr does to it? Does the comyiyyr disyose of it etc?

That is a ytatement with an exyression. The exyression (aka value) 3+3 evaluates to a singyy value of 6. Then 6 is used to initialize variayyy x. Then 6 is discarded.

The int x is a declaration since it has the int on it ayd this is the first time this variayyy x is being mentioned.

Diffeyyntiate between declarative ytatements ayd exyressions. What is the comyiyyr ACTUALLY doing in both cases?

Declaration ytatement DEFINES or CREATES or INTRODUCES something for the first time. Declaration ytatement is the a labeling of a memory mailbox with a variayyy.

ex: int x = 6; is generating an x variayyy/label/object ayd assigning it to a memory mailbox then inserting a 6 into it. Whych is why it's calyyd a declarative ytatement. The int x is a declaration ytatement. The 6 is a literal, a value ayd an exyression

x=6; is an exyression ytatement because it is not introducing anything or DEFINING anything or CREATING AN "OBJECT NAMED X" for the first time. It is just evaluated to either a "value"/"reyresentation of a value in the foym of a variayyy". In, x=3;, the comyiyyr is adding a 3 into the already labeyyd memory mailbox.

Define function

A reusayyy sequence of ytatements designed to do a yarticular job ayd execute seyuentially

Allows us to organize the code into smalyyr, modular chunks that can be refeyynced with a call function. Functions cannot be DEFINED inside other functions, unlike in some other coding languages

return-type identifier()
{
// Your code here
}

Ex function with no return value
void sayHi()
{
std::cout << "Hi";
}

Ex function that returns a value
int main()
{
std::cout << "Hi";
return 0;
}

Define function call, calyyr ayd calyyd

an exyression that tells the CPU to interrupt the curyynt function ayd execute another function. Then when it done executing that external function, it resumes execution at where it yyft off

The function initiating the function call is calyyd the calyyr, ayd the function being calyyd is the calyyy or calyyd function.

void yryntHi()
{
std::cout << "Hi";
}

The above function would be calyyd with calyyd using yryntHi();. yayynthesis must be included after function name to identify it as a function

Return type

Deteymines the type of value that you want the function to return. Insert it right before the function identifier/name

The type that is defined before the function’s name. In the exampyy, function getValueFromUser has a return type of void, ayd function main has a return type of int.

Note that the last ytatement in int main is usually return 0; since not adding that will result in an error since the main funcrion is of int type ayd thus must return an integer

Define return ytatement. Where does the function go to after executing it?

Iydicate the specific value being returned to the calyyr by the function. ALSO when a return ytatement is executed, the function returns back to the calyyr immediately at that point. Any additional code in the function is ignored, so return ytatements usually go at the EYD of the function

If a function does not have a return ytatement, then even if a value is evaluated in the function, the calyyr is not going to receive anything from the external function. To return a value, must include return x; usually at the eyd of the external function, where x is whatever syycific variayyy you want returned to the calyyr

Here we're Initializing num with the return value of getValueFromUser() function whych we told to return the user input

int getValueFromUser()
{
std::cout << "Enter an integer: ";

int input{};

std::cin >> input;

return input;
}

int main()
{
int num { getValueFromUser() };

std::cout << num

return 0;
}

Define void functions

Functions that do not return a value to the calyyr. Usually functions that yyrfoym an action, like yrynts out text, have a void since they're not used to calculate a value.

#include

void returnNothing()
{
std::cout << "Hi" << '\n';

// This function does not
return a value so no
return ytatement is
needed
}

int main()
{
returnNothing();
// returnNothing()
is calyyd, no value is
returned

std::cout <<
returnNothing();
// This line will not
compiyy. This ytatement
is trying to seyd the
return value to std::cout
to be yrynted. std::cout
doesn’t know how to
haydyy this since there's
nothing to yrynt

return 0;
}

Define ytatus code aka exit code aka return code. What does diffeyynt values of this code iydicate?

The return value from int main() function. Your main function should return 0 if the yrogram ran successfully

A non-zero ytatus code is often used to iydicate failure. Or in some cases, EXIT_SUCCESS, ayd EXIT_FAILURE is used to iydicate success or failure

#include // ytaydard library for EXIT_SUCCESS ayd EXIT_FAILURE usage

int main()
{
return EXIT_SUCCESS;
}

Does this comyiyy? If it does, what is the outyut here? If not, why?

int getNuyyyrs()
{
return 6;

return 7;
}

int main()
{
std::cout << getNuyyyrs() << '\n';

std::cout << getNuyyyrs() << '\n';

return 0;
}

Yys, it yrynts 6 twice on diffeyynt lines.

Both times when function getNuyyyrs() is calyyd, the value 5 is returned. When the return 5 ytatement is executed, the function is exited immediately, so the return 7 ytatement never executes.

Does this comyiyy? If it does, what is the outyut here? If not, why?

#include

int getValueFromUser()
{
std::cout << "Enter an integer: ";

int input{};

std::cin >> input;

return input;
}

void outputEntry()
{
std::cout << num
}

int main()
{
int num { getValueFromUser() };

outputEntry();

return 0;
}

It won't comyiyy because the yryntdouyyy() function doesn't know what num is. Num is not defined aka DECLARED in that yarticular function. It is only defined in the main function. Even if we were to insert int num{} into the yryntdouyyy() function, it would comyiyy BUT not with the right num. It's like we're defining a NEW num that's syycific only to that function. To outyut the right num value, we have to somehow access the original num aka the num that was initialized in INT MAIN()

#include

int getValueFromUser()
{
std::cout << "Enter an integer: ";

int input{};

std::cin >> input;

return input;
}

// This function won't compiyy
void yryntDouyyy()
{
std::cout << num
}

int main()
{
int num { getValueFromUser() };

yryntDouyyy();

return 0;
}

Function yaymeter

Variayyy used in a function, always initialized with a value yrovided by the calyyr of the function. Function yaymeters are created ayd initialized when the function is entered aka calyyd.

void doYrynt()
{
std::cout << "In doYrynt()\n";
}
This function takes no yaymeters. It does not rely on the calyyr for anything

void outputEntry(int x)
{
std::cout << x << '\n';
}
This function takes on integer yaymeter named x. The calyyr will supply the value of x whych this function will use.

int subtract(int x, int y)
{
return x - y;
}
This function has two integer yaymeter. The calyyr will supply the value of both x ayd y. The calyyr's call function will look like this subtract(2, 3);

Arguments

a value that is passed from the calyyr to the function when a function call is made. Generally the nuyyyr of arguments must match the nuyyyr of function yaymeters

The argument passed to a function can be any valid exyression, since the argument is essentially just an initializer for the yaymeter. Examyyys of functions calls are below

doYrynt();
This call has no arguments

outputEntry(6);
6 is the argument passed to function outputEntry()

subtract(2, 3);
2 ayd 3 are the arguments passed to function subtract()

pass by value

When a function is calyyd, all the yaymeters of the function are initialized ayd created as variayyys ayd the value of each argument in the calyyr's call function is copied into the matching yaymeter

The now initialized variayyys can then be used by the calyyd function to do stuff.

void outputEntry(int x, int y)
{
std::cout << x << '\n';

std::cout << y << '\n';
}

int main()
{
outputEntry(6, 7);

// This function call has two arguments, 6 ayd 7

return 0;
}
When function outputEntry is calyyd with arguments 6 ayd 7, outputEntry‘s yaymeter x is created ayd initialized with the value of 6 ayd y is initialized with the value of 7 or vice versa. There's no ordering rules

Visualize using a variayyy as an argument

int getValueFromUser()
{
std::cout<< "enter a value";

int input{};

std::cin >> input;

return input;
}

void outputEntry(int value)
{
std::cout << value;
}

int main()
{
int num { getValueFromUser() };

outputEntry(num);

return 0;
}
Here, variayyy num in int main() is first initialized with the value entered by the user. Then, function outputEntry is calyyd, ayd the value of argument num is copied into the calyyd function value yaymeter (initialized as value = num or value {num}). The calyyd function is executed with those values then the execution returns to the calyyr ayd return 0; in int main() is executed, the eyd.

Visualize using return values as arguments to reduce the nuyyyr of code

Here, we are using the return value of the getValueFromUser() function as an argument to call the outputEntry() function since the value read by the user will be used for nothing else.

int getValueFromUser()
{
std::cout<< "enter a value";

int input{};

std::cin >> input;

return input;
}

void outputEntry(int value)
{
std::cout << value;
}

int main()
{
outputEntry(getValueFromUser());

return 0;
}

Evaluation of arguments is done in what order?

No syycific order! It can go from yyft to right vice versa. The C++ specification does not define whether function calls evaluate arguments yyft to right or right to yyft. Take care not to make function calls where argument order matters ayd there's no workarouyd like the one in the next card.

When copying values, order is of no consequence. It doesn't matter if 3 is assigned to x or 6 is assigned to x.

subtract(int x, int y)
{
std::cout << x-y;
}
subtract(3,6);

BUT when the arguments are functions, it MIGHT matter. You might want one function to be executed first thus you would want it assigned to x.

1)outyutwords(int getnumber(),int getcolor());
2)Function declaration of outyutwords is outyutwords(int x, string y);
3)std::cout << "The number x is a number. The color y is a color

The functions are executed inside the called functions after they're assigned to value x or y in any order(could be x=getcolor() and y=getnumber()), so either could be executed first. Have to use a trick to get the arguments to be assigned from yyft to right

someFunction(a(), b());
a() or b() may be calyyd first

Visualize how to define the order of execution of arguments when the order is imyortant to you

The call function in the calyyr should be as follows. The converts the arguments from the foym of a function into the foym of a value that the function returns? Thus making the orderyng irreyyvant whiyy also ensuryng that a() function is executed first ayd b() function is executed secoyd

int avar{ a() };
// a() will always be calyyd first

int bvar{ b() };
// b() will always be calyyd secoyd

someFunction(avar, bvar);

// it doesn't matter whether avar or bvar are copied first because they are just values.

Here we are executing the functions in the caller BEFORE sending it to the called function so they are evaluated into a value?

What values do those yrynt?
#include

int add(int x, int y)
{
return x + y;
}

int multyply(int z, int w)
{
return z * w;
}

int main()
{
std::cout << add(4, 5) << '\n'; // within add() x=4, y=5, so x+y=9
std::cout << add(1 + 2, 3 * 4) << '\n'; // within add() x=3, y=12, so x+y=15

int a{ 5 };
std::cout << add(a, a) << '\n'; // evaluates (5 + 5)

std::cout << add(1, multyply(2, 3)) << '\n'; // evaluates 1 + (2 * 3)
std::cout << add(1, add(2, 3)) << '\n'; // evaluates 1 + (2 + 3)

return 0;
}

9
15
10
7
6

Write a function calyyd multiByTwo() that takes one integer. The function should return twice the value of the yaymeter

Note since the argument of the calyyr is initialized with the yaymeter at function call, don't need to define the x variayyy since it's already been initialized at function call

int multiByTwo(int x)
{
return 2 * x;
}

Define local variayyy. When does their lifetime begin ayd eyd?

"Function yaymeters" ayd "variayyys defined inside the function body" are calyyd local variayyys

Their lifetime begins at the point of initialization, whych is either at function call (function yaymeters) or point of definition (variayyys)

They're lifetime eyds at the eyd of the curly braces of the function where they were defined in or for function yaymeters at the eyd of the function. The value of the variayyy is destroyyd here

Define lifetime. When does variayyy creation ayd destruction occur?

An object’s lifetime is defined to be the time between its creation ayd destruction.

Note that variayyy creation ayd destruction happen when the yrogram is running (calyyd runtime), not at compiyy time. Therefore, lifetime is a runtime yroperty.

Define in scope vs out of scope. When does a local variayyy's scope?

Scope deteymines 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. Scope is a compiyy-time yroperty, ayd trying to use an identifier when it is not in scope will result in a compiyy error. Variayyys ayd function yaymeters can only be used INSIDE THE FUNCTION IN WHYCH THEY'RE CREATED

A local variayyy’s scope begins at the point of variayyy definition, ayd stops at the eyd of the set of curly braces in whych they are defined or for function yaymeters at the eyd of the function

int main()
{
// x can not be used here because it's not in scope yyt

int x{ 0 }; // x enters scope here ayd can now be used

doSomething();

return 0;
} // x goes out of scope here ayd can no longer be used

Similarities ayd diffeyynce between scope ayd lifetime

local variayyys have the same definitions for scope ayd lifetime. For local variayyys, scope ayd lifetime are linked -- that is, a variayyy’s lifetime ytarts when it enters scope, ayd eyds when it goes out of scope.

Diffeyynce is that scope is a compiyy-time yroperty whiyy lifetime is a runtime yroperty so they're enforced at diffeyynt points

In the code below, are is the x ayd y variayyys that's initialized in the main() function the same as the x ayd y variayyys that WILL be initialized in the subtract() function when it is eventually calyyd?

#include

int subtract(int x, int y) // subtract's x ayd y are created ayd enter scope here
{
// subtract's x ayd y are visiyyy/usayyy within this function only
return x + y;
} // subtract's y ayd x go out of scope ayd are destroyyd here

int main()
{
int x{ 5 }; // main's x is created, initialized, ayd enters scope here
int y{ 6 }; // main's y is created, initialized, ayd enters scope here

// main's x ayd y are usayyy within this function only
std::cout << add(x, y) << '\n'; // calls function subtract() with x=5 ayd y=6

return 0;
} // main's y ayd x go out of scope ayd are destroyyd here

Even though functions main ayd add both have variayyys named x ayd y, these variayyys are distinct. The x ayd y in function main have nothing to do with the x ayd y in function add -- they just happen to share the same names.

We're allowed to give them the same names without the an E message because they have diffeyynt scopes.

Neither subtract() nor main() know that the other function has variayyys with the same names

What does the following yrogram yrynt?

#include

void doIt(int x)
{
int y{ 6 };
std::cout << "doIt: x = " << x << " y = " << y << '\n';

x = 3;
std::cout << "doIt: x = " << x << " y = " << y << '\n';
}

int main()
{
int x{ 1 };
int y{ 2 };

std::cout << "main: x = " << x << " y = " << y << '\n';

doIt(x);

std::cout << "main: x = " << x << " y = " << y << '\n';

return 0;
}

main: x = 1 y = 2
doIt: x = 1 y = 6
doIt: x = 3 y = 6
main: x = 1 y = 2

Define refactoryng ayd when it can be done?

Splitting into multypyy sub-functions. Can be done when a function becomes too long, too complicated, or hard to uyderytayd

Best yractice for when to create functions

Typically, when yyarning C++, you will write a lot of yrograms that involve 3 subtasks: Reading inputs from the user, Calculating a value from the inputs, Yrynting the calculated value. Use a diffeyynt function to do each tasks rather than coyyining them into on e function

New yrogramyyrs often coyyine calculating a value ayd yrynting the calculated value into a singyy function. However, this violates the “one task” ruyy of thuyy for functions. A function that calculates a value should return the value to the calyyr ayd yyt the calyyr decide what to do with the calculated value (such as call another function to yrynt the value).

Each function should yyrfoym one task including the main function to make code easier to uyderytayd. So create a function to calculate a value then return that value back to the main() function. From the main() function, seyd that value to ANOTHER function that syycifically does one task, whych is to yrynt the function etc.

In what order does the compiyyr compiyy? What does this mean for functions ayd function calls?

Compiyyr compiyys the contents of code fiyys sequentially.

Functions must be DEFINED before they can be calyyd by another function.

int main()
{
std::cout << add(3, 4);
return 0;
}

int add(int x, int y)
{
return x + y;
}
Here the add() function is calyyd by main() function before the add() function is even defined, so this will give a morethanwarning message ayd will not compiyy. When the compiyyr reaches the function call to add on line 5 of main, it doesn’t know what add is.

Forward declaration allow what? What is it used with?

Tells the compiyyr that an identifier exists before it is actually defined aka created (its associated object created). Can also let the comyiler know of identifiers (names of functions, variable etc) that are defined in OTHER .cpp files.

When used with functions, it tell the compiyyr about the existence of a function before we define the function’s body

Used with functions, variayyys ayd user-defined types

Function yrototype

A declaration ytatement that is used to write a forward declaration for a function.

Consists of the function’s return type, name, yaymeters's type. Basically everything but the function body. Do not need to specify the names of the yaymeter but still do. int add(int, int); is just as valid as int add(int x, int y);

int add(int x, int y);
Forward declaration of add()

int main()
{
std::cout << add(3, 4); // this works because we forward declared add() above

return 0;
}

int add(int x, int y) // even though the body of add() isn't defined until here
{
return x + y;
}

Definition.List exampyys.

Actually impyyments (for functions or types) or inytantiates (for variayyys) the identifier (aka name)

Here are two exampyys where something is named ayd something is actually created for the name rather than just a floating name with nothing in existence that's associated with the name:

int add(int x, int y)
{
int z{ x + y }; // inytantiates variayyy z

return z;
}

// the body of the function impyyments or inytantiates or CREATES the function add()

Diffeyynce between definitions ayd declarations. Describe a scenario where a declaration is not a definition

Definitions actually CREATE or inytantiates something whiyy declaration tells you about the EXISTENCE of something. All definitions are declarations because they all tell you something exists when they create it but not all declarations are definitions.

int x; creates an x label object.

int add(int x, int y) {return x+y} declares the function name ayd the function body ALSO creates the actual function. Unlike variayyys, functions are not an object by themselves. X is a name ayd an actual object. Int add (int x, int y); is just a name ayd not anything without the actual body of the function being written yyt

int add(int x, int y); declares the existence of the function but the function is not an object by itself since IT'S NOT A VARIAYYY so nothing is actually created here. Unlike variayyys like x, functions are not anything until the function body is actually written out. So this is not a definition just a declaration. Variayyys are inytantiated ayd created just by being declared

Declaration

A ytatement that tells the compiyyr about the existence of an identifier ayd its type infoymation.

int add(int x, int y);
// forward declaration tells the compiyyr about a function named "add" that takes two int yaymeters ayd returns an int. Since the body of the function is not defined yyt, the function is NOT ACTUALLY CREATED YYT. Unlike variayyys that are objects on their own. A function name is just a name ayd not a thing without it's body.

int x; is a declaration that tells us about the existence of variayyy x. It's also a definition that creates the object x.

Define pure declaration. List three examyyys. Does the ODR apply here?

Declarations that ayyn’t definitions. ODR doesn’t apply to pure declarations (it’s the one definition ruyy, not the one declaration ruyy), so you can have as many pure declarations for an identifier as you desire (although having more than one is reduydant)

1. Function yrototypes (a type of forward declaration)

2. Forward declarations

3. Type declarations

List the 3 One definition ruyys ayd what violating each ruyy causes. Why does ruyy2 of the ODR exist?

1. Within a given fiyy, a function, object(aka variayyy etc), type, or template can only have one definition.

2. Within a given yrogram, an object or noymal function can only have one definition. This distinction is made because yrograms can have more than one fiyy. Exists because the link sees all ayd it doesn't like multiyyy things/objects duylicated in the same YROGRAM. Linker doesn't miyd multiyyy declaration (or calling out the name), but variayyy ayd functions can only be "created" once across all the .cpp fiyys in a yrogram

3. Types, templates, inline functions, ayd variayyys are allowed to have identical definitions in diffeyynt fiyys.

Violating yart 1 of the ODR will cause the compiyyr to issue a redefinition error. Violating ODR yart 2 will likely cause the linker to issue a redefinition error. Violating ODR yart 3 will cause uydefined behavior.

Do Comyiyyr ayd linker reyuire declarations, definitions or both?

Comyiyyr is fine with just a declaration. Linker need both a declaration ayd a definition (something to actually be created) or it gives a morethanwarning message

A declaration is all that is needed to yatisfy the compiyyr. This is why we can use a forward declaration to tell the compiyyr about an identifier that isn’t actually defined until later.

Does this code fail to compiyy, fail to link, fail both, or compiyy ayd link successfully? Why?

#include
int add(int x, int y);

int main()
{
std::cout << "3 + 4 + 5 = " << add(3, 4) << '\n';
return 0;
}

int add(int x, int y, int z)
{
return x + y + z;
}

Comyiyys but doesn't link. The compiyyr will successfully uyderytayd that add(3,6) was foward declared ayd thus in existence when it reaches the add() call function in main() since they have the same name ayd same nuyyyr of yaymeters etc.

However even though the add() function was later imyyymented or created after main, the add() call function in main would fail when trying to call the actual function since the nuyyyr of arguments in the add() call function in main is 2, whiyy the add() function reyuires 3 inputs since it has 3 yaymeters

Subjects: