Learning C++ - Chapter 2

Ace your homework & exams now with Quizwiz!

A signed char can hold a number between...

-128 and 127

An unsigned char can hold a number between...

0 and 255

Char is defined by C++ to always be what size?

1 byte

Fixed-width integers

A set of integers that are guaranteed to have the same size on any architecture.

For the sake of this tutorial series, what character set will we use?

ASCII

What happens if we do not declare an integer variable signed or unsigned?

All integer variables except char are signed by default. Char can be either signed or unsigned by default (but is still usually signed for conformity)

size_t

An unsigned integral value that is typically used to represent the size or length of objects.

Double values have how many digits of precision?

Between 15 and 18 digits of precision, with most having at least 16 significant digits.

What is the difference between putting symbols in single and double quotes?

Chars go in single quotes Text put between double quotes is called a string

What two main uses of ' , ' are not considered use of the comma operator?

Commas used to separate the parameters in a function call Commas used to separate variables when declaring multiple variables on the same line.

What rule should you follow regarding side effects?

Don't use a variable that has a side effect applied to it more than once in a given statement. If you do, the result may be undefined.

With floating point variables, which type should you prefer between float and double? Why?

Favor DOUBLE over float, unless space is at a premium, as the lack of precision in a float will often lead to inaccuracies.

An 'f' suffix is used to denote a literal of what type?

Float

Can floating point data types be signed or unsigned?

Floating point types are always signed.

Why should you be careful when using integer division in C++?

If the result is not an integer, you will lose the fractional part of your result. For example, 8 / 5 = 1.6, but as an integer variable, your result would be cut off to just 1.

constexpr

Keyword that ensures a constant must be a compile-time constant (precedes/follows variable type, but should precede, just like const)

Why are symbolic constants usually better than literal constants?

Literal constants (a.k.a. Magic Numbers) can make your code harder to understand; they do not have names to provide context, and you cannot change all instances of their values without changing each individual one.

Void

No type

When should you use the conditional operator?

Only use the conditional operator for simple conditionals where it enhances readability.

You should NEVER mix these two types of integers

Signed and unsigned

Escape sequences

Special commands that can be used inside of double quotes. An escape sequence starts with a '\', and then a following letter or number.

Data type

Tells us how to interpret the contents of memory in some meaningful way (i.e. integers)

Significant digits

The digits in a decimal number that carry meaning contributing to the precision or accuracy of the quantity.

size_t will typically be what kind of variable in a 32-bit application? A 64 bit application?

a 32-bit unsigned integer; a 64-bit unsigned integer

We should use constexpr for...

any variable that should not change value after initialization and whose initializer is known at compile-time.

Avoid using the ______ operator, except in 'for loops'.

comma

This operator has the lowest precedence of any operator

comma

What is the format of the sizeof operator? What is its function?

sizeof(type) sizeof(variable) Returns the size of type or variable in bytes

if (expression) statement 1; // If "expression" evaluates to a non-zero value, then...

statement 1 is executed

if (expression) statement 1; else statement 2; // If "expression" evaluates to a zero value, then...

statement 2 is executed instead

If you want std::cout to print "true" or "false" instead of "1" or "0", you can use...

std::boolalpha

What is the symbol for the conditional operator? What is the format of the conditional operator? What is its function?

symbol: ?: Format: c ? x : y If c is nonzero(true) then evaluate x, otherwise evaluate y.

In many applications, a symbolic constant needs to be used...

throughout your code (not in just one location

Boolean values are not actually stored/evaluated as the words "true" or "false"; instead, they are stored as integers: true becomes _____ false becomes _____

true becomes 1 false becomes 0

Just like variables, all literals have a ______

type

Integer type

variable that can hold only non-fractional numbers

You don't need to use char16_t and char32_t unless...

you are planning on making your program Unicode compatible and are using 16-bit and 32-bit Unicode characters.

The proper format for defining symbolic constants:

#ifndef CONSTANTS_H #define CONSTANTS_H // define your own namespace to hold constants namespace constants { constexpr double pi(3.14159); constexpr double avogadro(6.0221413e23); constexpr double my_gravity(9.2); // m/s^2 -- gravity is light on this planet // ... other related constants } #endif

/* How could the following be rewritten using the conditional operator? */ if (condition) expression; else other_expression;

(condition) ? expression : other_expression;

In mathematical terms, an n-bit signed variable has a range of...

-(2^(n - 1)) to 2^(n-1) - 1

There are three different types of floating point data types:

-Float -Double -Long double

The range of an integer variable is determined by two factors:

-Its size (in bits) -Its sign ("signed" or "unsigned").

C++ has two types of constants:

-Runtime constants -Compile time constants

When printing the fixed width integer "int8_t", it is usually treated as...

...a signed char, and will generally print as a char instead of an integer.

When user input is stored as a char...

...only the first character is held. Consequently, the rest of the user input is left in the input buffer, and can be accessed with subsequent calls to cin.

Floating point numbers often have small...

...rounding errors, even when the number has fewer significant digits than the precision

Floating point numbers are great for...

...storing very large or very small numbers, including those with fractional exponents.

The number of digits of prevision a floating point variable has depends on both...

...the size (floats have less precision than doubles), and the particular value being stored (some values have more precision than others.

/* Because the << operator has higher precedence than the ?: operator, how would the following statement be evaluated? */ std::cout << (x < y) ? x : y;

// it would evaluate as: (std::cout << (x > y)) ? x : y; /* that would print 1 (true) if x > y, or 0 (false) otherwise */

The explicit use of keyword void to mean "no parameters" in a function is a holdover from C, and is not required in C++. What is a better way to write this?

//Obsolete way int getValue(void) //C++ way int getValue( ) //Just leave the parameter list empty to indicate that it is void

To use an octal literal, prefix your literal with...

0

In mathematical terms, an n-bit unsigned variable has a range of...

0 to (2^n) - 1

Count to 10 in binary:

0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010

To use a hexadecimal literal, prefix your literal with...

0x

How should you go about defining symbolic constants? (4 steps)

1). Create a header file to hold the constants. 2). Inside this header file, declare a namespace. 3). Add all your constants inside the namespace (make sure they're const). 4). #include the header file wherever you need it.

What are the three most common mistakes new programmers make when defining multiple variables in the same statement? Which is the most dangerous?

1). Giving each variable a type when defining it: int a, int b; // wrong int a, b; //right 2). Defining variables of different types on the same line: int a, double b; // wrong (compiler error) 3). Mistakenly trying to initialize both variables using one initialization statement (most dangerous, the compiler will probably not catch it): int a, b = 5; // wrong (a is uninitialized!) int a= 5, b= 5; // correct

In what contexts is type "void" used?

1). Most commonly, as a way to indicate that a function does not return a value. 2). In C, as a way to indicate that a function does not take any parameters: 3). Void pointers (not yet discussed)

C++ has FIVE different fundamental integer types available for use:

1). char 2). short 3). int 4). long 5). long long

Long double values have a minimum precision of...

15, 18, or 33 significant digits depending on how many bytes it occupies

How do you write the following numbers in binary? How many bits does each consist of? Decimal Value: 2 3 6 9 14

2: 10 (2 bits) 3: 11 (2 bits) 6: 110 (3 bits) 9: 1001 (4 bits) 14: 1101 (4 bits)

A variable with 'n' number of bits can hold ____ possible values. For example, an 8-bit byte can store ____ possible values.

2^n; 256

What are the 6 relational operators?

==, !=, >, <, >=, <=

String

A collection of sequential characters

Magic number

A hard-coded literal (usually a number) in the middle of the code that does not have any context.

Signed integer

A signed integer is a variable that can hold both negative and positive numbers.

How does static_cast work?

A variable is passed in. That variable is evaluated to produce its value, which is then converted to the new type.

Uninitialized variable

A variable that has not been initialized will have a meaningless value until you assign it a valid one.

Floating point

A variable type that can hold real numbers as well as fractional/decimal parts. i.e. 4320.0, -3.33, or 0.01226

Variable initialization

Assigning a value to a variable at declaration.

Float values have how many digits of precision?

Between 6 and 9 digits of precision, with most having at least 7 significant digits

Bit

Binary digit; 0 or 1; the smallest unit of memory.

Runtime constants

Constants whose initialization values can only be resolved at runtime (when your program is running) i.e. through user input

Compile-time constants

Constants whose values can be resolved at compile time (when your program is compiling)

Unsigned integer

Declaring a variable as unsigned means that it cannot store negative numbers, but it can store positive numbers that are twice as large.

// What will the following snippet print? char ch(97); std::cout << ch;

Despite being initialized with an integer, when used in cout, it will still print as a char. In this case, it prints "a"

Favor ________ integers over _________ integers.

Favor SIGNED integers over UNSIGNED integers unless you have a specific need for them, as unsigned integers are more prone to unexpected bugs and behaviors than signed integers.

Direct initialization

Form of initialization that does not include an =. Uses parenthesis instead. format: int nValue(5);

Copy initialization

Form of initialization that uses an =. The newly created object is a copy of the given initializer.

Why isn't the size of integer variables fixed?

Going back to C, when performance was of utmost concern, C intentionally opted to leave the size of an integer open so that the compiler implementers could pick a size for int that performs best on the target computer architecture.

What happens if a conditional is an expression that does not evaluate to a boolean value?

If the conditional evaluates to a non-zero value, then the statement associated with the 'if' statement executes (as if it were "true").

/* What will happen with this bool depending on what parameters x and y are? */ bool isEqual(int x, int y) { return (x == y); // operator== returns true if x equals y, and false otherwise }

If x and y are equal (i.e. 5 = 5), it will evaluate as true, and return 1. If x and y are not equal, it will evaluate as false and return 0.

Why should you never use magic numbers?

In addition to not providing context as to what they are being used for, they pose problems if the value needs to change.

The conditional operator evaluates as ______________. Meaning...

It evaluates as an expression (while if/else evaluates as a set of statements), meaning the conditional operator can be used in some places where if/else can not.

Const

Make a variable constant (unmodifiable) Can be placed before or after the variable type, but should be placed before by convention. Const variables MUST be initialized upon definition.

/* What does the following program print, and WHY? */ bool b(false); if (b) std::cout << "b is true" << std::endl; else std::cout << "b is false" << std::endl;

Prints: b is false Variable 'b' evaluates to its value, which in this case is false. False evaluates to value 0. Consequently, the first statement does not execute, but the 'else' statement does.

Condition/Conditional expression

The "expression" component of an if-statement, given the format: if (expression) statement1; or if (expression) statement1; else statement2;

/* Why are these char initializations not the same? */ char ch(5); char ch('5');

The first initializes with integer 5, while the second initializes with code point for '5' (53).

Just as the unary minus operator (-) can be used to make an integer negative, what do we use to flip a boolean value from true to false/false to true?

The logical NOT operator (!)

Octal

The octal number system is base 8, using only digits 0 through 7.

Range

The set of specific values that a data type can hold.

Byte

The smallest addressable unit of memory

In conditional statements, what must you remember regarding the two expressions?

The type of the expressions must match or be convertible. i.e. you cannot have an integer and a string literal, as they don't match and there is no way for the compiler to convert the string literal into an integer. You will get an error.

What are the downsides of fixed-width integers?

They may not be supported on architectures where those types can't be represented. They may also be less performant than the built-in types on some architectures.

When should you use '\n' vs "std::endl"?

Use "std::endl" when you need to ensure your output is output immediately (i.e. when writing a record to a file or updating a progress bar). This may have a performance cost. '\n' is preferable in mostly all other cases.

What is the better way to create symbolic constants? Why?

Use const variables These will show up in the debugger, and follow the same scope rules as variables. i.e. constexpr int maxStudentsPerClass { 30 }; constexpr int maxNameLength { 30 };

How would you access your constants stored in a header from your .cpp file?

Use the scope resolution operator (::) i.e. #include "constants.h" double circumference = 2 * radius * constants::pi;

Static_cast

Used to convert between fundamental data types (for example, from a char to an int, or vice versa) format: static_cast<newtype>(expression)

What is the bad way to define symbolic constants? Why?

Using object-like macros with substitution text (#define) #defined symbolic constants do not show up in the debugger (since macros are resolved by the preprocessor). #defined symbolic constants always have file scope, meaning a value #defined in one piece of code may have a naming conflict with a value #defined within the same file later

What happens if we assign a 6 bit value to a 4 bit variable?

We get overflow: our variable will only store the 4 least significant (rightmost) bits, and the excess bits are lost.

Copy assignment

When a variable is given a value after it has been defined. int nValue; nValue = 5;

Symbolic constant

a name given to a constant literal value

char16_t and char32_t

added to C++11 to provide explicit support for 16-bit and 32-bit Unicode characters (8-bit Unicode charaters are already supported by the normal char type)

If the default type of a literal is not as desired, you can change the type of a literal by...

adding a suffix

What does static_cast take as input?

an expression

We should use const for...

any variable that should not change after initialization and whose initializer is not known at compile-time

Type cast

creates a value of one type from a value of another type.

By default, floating point literal constants have a type of...

double

By default, floating point literals default to what type?

double

C++11 also defined two alternative sets of fixed-width integers:

fast and least

If you wanted to write a floating point literal of type "float," how would you write it and why?

float f = 5.0f; // The 'f' suffix converts the literal into a float value.

Static casting doesn't support range checking, meaning

if you cast an integer that is too big to fit into a char, you'll overflow your char

Always remember to ____________ your fundamental variables as soon as possible after defining them.

initialize/assign a value

Due to an oversight in the C++ specification, most compilers define and treat _________ and _________ to types signed char and unsigned char respectively, but this is not required. (fixed-width integers)

int8_t and uint8_t

Regarding fixed-width integers, avoid _______ and ________. If you do use them, note that they are often treated like _______.

int8_t and uint8_t; chars

If you NEED a variable guaranteed to be a particular size and want to favor memory conservation over performance, use...

int_least#_t

C++ has two kinds of constants:

literal and symbolic

\n

new line

Const variables can also be initialized from...

non-const values

Overflow

occurs when bits are lost because a variable has not been allocated enough memory to store them (if we put a number outside the data types range into a variable).

Symbolic constants can include, for example...

physics or mathematical constants that don't change (i.e. pi or the golden ratio), or application specific "tuning values" (i.e. gravity and friction coefficients).

The ?: operator has very low _________, so if doing anything other than assigning the result to a variable, the ?: statement needs to be wrapped in parenthesis.

precedence

By default, char may be signed or unsigned, though it is usually...

signed

Generally, the _________ keyword is not used (since it's redundant), except on chars (when necessary).

signed

Range of 1 byte variable signed: Range of 1 byte variable unsigned:

signed: -128 to 127 unsigned: 0 to 255

Characters are always placed between...

single quotes

Chars are always placed inside of...

single quotes (putting more than one symbol in the single quotes is illegal)

When inputting boolean values, what must you remember about std::cin?

std::cin only accepts two inputs for boolean variables: 0 and 1 (NOT true or false). Any other inputs will cause std::cin to silently fail.

You can turn off std::boolalpha by using...

std::noboolalpha

Function defined in header <iomanip>, used to override default precision in cout/output

std::setprecision

Fundamental data types

the basic data types built into the C++ language; also called basic types, primitive data types, or built-in data types

The best day to output a char as a number instead of a character is to...

use a type cast.

Consider the fraction 1/10. This is easily represented as a decimal (0.1), however, in binary, it is represented by an infinite sequence (0.0001100110011...). Because of this, when we assign 0.1, we use a ________ type, because...

we use a DOUBLE type, because a float type will cause precision problems.

wchar_t

wide character used to hold characters that take more than one byte to represent. Should be avoided in almost all cases. Its size is implementation-defined, and is not reliable.

What is the format of the comma operator? What is its function?

x, y Evaluate x, then y; returns value of y

Uniform initialization has the added benefit of disallowing...

..."narrowing" type conversions, meaning that if you try to use uniform initialization to initialize a variable with a value it can not safely hold, the compiler will throw a warning or error.

The modern standard is that a byte is comprised of...

...8 sequential bits

Fast type gives you...

...an integer that's the fastest type with a width of at least # bits (where # = 8, 16, 32, or 64) For example, int_fast32_t will give you the fastest integer type that's at least 32 bits

What writing floating point literals, it is always convention to include...

...at least one decimal place (i.e. 30.0). This helps distinguish floating point values from integer values.

The size of a given data type is actually partially dependent on the...

...compiler and/or computer architecture

The standard fixed-width integers adopted by C++ can be accessed by...

...including the cstdint header #include <cstdint>

If you NEED a variable guaranteed to be a particular size and want to favor performance, use...

...int_fast#_t

Rounding errors can be magnified when...

...mathematical operations are performed on these values.

Memory is organized into sequential units called...

...memory addresses

size_t is defined to be big enough to hold...

...the size of the largest object creatable on your system (in bytes). For example, if size_t is 4 bytes, the largest object creatable on your system can't be larger than the largest number representable by a 4-byte unsigned integer (4,294,967,295)

Least type gives you...

...the smallest integer type with a width of at least # bits (where # = 8, 16, 32, or 64). For example, int_least32_t will give you the smallest integer type that's at least 32 bits.

Overflow by assigning a value above the maximum of a variable's range will result in...

...the value wrapping around to the bottom of the range (lowest possible value)

Overflow by assigning a value below the minimum of a variable's range will result in...

...the value wrapping around to the top of the range (highest possible value)

Because the size of char, short, int, and long can vary depending on the computer architecture and/or compiler, it can be useful to refer to integers by...

...their size rather than a name (often referrig to them by the number of bits a variable of that type is allocated). i.e. "32-bit integer" instead of "long"

In scientific notation, we prefer to keep trailing zeros after a decimal, because...

...those digits impart useful information about the precision of the number.

Results of overflow are only predictable for...

...unsigned integers. (Overflowing signed integers or non-integers may result in different values on differnt systems)

Variables cannot be defined with a type of...

...void (no type)

You should avoid defining multiple variables on a single line if...

...you are initializing any of them

To explicitly declare a variable as signed...

..you can use the 'signed' keywords, by placing it before the variable type i.e. signed short s;

What are two key reasons why it is useful to know how much memory a variable takes up?

1). The more memory a variable takes up, the more information it can hold. 2). Computers have a finite amount of free memory. This is more a concern for bigger programs holding large amounts of variables (i.e. 100,000), where the difference between using 1-byte and 8-byte variables can be significant.

When deciding which form of initialization to use, from most preferred to least, you should use...

1). Uniform initialization int value{5} 2). Direct initialization int nValue(5); 3). Copy initialization int nValue = 5

What are the advantages of placing a variable as close to the first use of the variable as possible?

1). Variables that are defined only when needed are given context by the statements around them. 2). It tells is this variable does not affect anything above it, making our program easier to read. 3). It reduces the likelihood of inadvertently leaving a variable uninitialized because we can define and then immediately initialize it with the value we want it to have.

The two special categories of floating point numbers:

Inf (infinity) NaN (not a number)

Uniform initialization

Initializing a variable with braces. (will initialize to zero/nothing if the braces are empty). int value{5}

Where did older C compilers force users to define all variables in a function? (obsolete) What is the new standard style for placing variables in a function?

They used to require variables be defined at the top of a function The proper C++ style is to define variables as close to the first use of that variable as you reasonably can.

Sizeof

Unary operator that takes either a type or a variable, and returns its size in bytes.

C++ does not provide a way to do what kind of assignments?

Uniform or direct assignments; there are only copy assignments. (remember, this isn't initialization!)

When defining short/long integers, what format should you write them in to avoid confusion?

Write them WITHOUT the INT suffix. Both forms are valid, but the shorthand version will avoid confusion. //preferred long long identifier; //valid but not preferred long long int identifier;

What does a char hold? What makes it unique?

a 1 byte integer. However, instead of interpreting the value of the char as an integer, the value of a char variable is typically interpreted as an ASCII

You should not use __________ integers unless it absolutely makes more sense to do so in a given scenario.

unsigned

size_t can vary in size, but is guaranteed to be ____________ and at least ___ bits, but on most systems will be equivalent to the address width of the application.

unsigned; 16;


Related study sets