Learning C++
Learning C++
Code starts with #include <iostream>, a library to understand the - AND (&&) : if one or all is false it will be false
code that will be written with C++ - OR (II): If one or all is true then it will be true
Main function (main() {}) is the entry code and the code inside the - NOT (!): Negate whatever you gave it
functions will be executed in order. Output Formatting
3 COMPONENTS OF C++ : - Link for references:
1. Core features EX. Defining variable https://en.cppreference.com/w/cpp/io/manip
2. Standard library EX. #include <iostream> and <string> - #include <ios> and #include <manip>
3. STL – part of c++ standard library, collection of things - std::endl – like a \n and will occupy the new line
TYPES OF VARIABLES: - std::flush – sends the data directly to the device
Int – whole numbers - std::setw(numWidth) - set the width of the text to make it look
Double & float – fraction, decimal good when display in screen
Char – characters - std::right – display the data starting to the right
Bool – true or false - std::internal – justify
Void – meaningless / valueless - std::showpos – shows positive and negative sign before the num.
Auto – auto detect by compiler - std::dec, std::hex, std::oct – shows the number in this format
------------------------------------------------------------------------------------ - std::uppercase, std::lowercase – change the text
CHAPTER 4: OPERATIONS ON DATA: - std::scientific – scientific notation
Precedence and Associativity - std::setprecision(num) – set the precision of decimal points
- Precedence: which operation is to be done first.
C++ Operator Precedence – search on google
- Associativity: which directions to do the calculations.
Postfix Increment/Decrement
- var++ / ++var - increment by one only.
- var--/ --var – decrement by one only.
Compound Assignment
- +=, -=, *=, /=, %= :: shortcut to add, sub, mul, div, rem the
variable itself to another var
Relational Operators (<, >, <=, >=, ==, !=)
- std::boolalpha – shows true/false instead 1/0
std::sin()
std::tan()
Ref: https://en.cppreference.com/w/cpp/header/cmath
Weird Integral Types
Chapter 5: Flow Control
Flow Control Introduction
If Statements
Syntax: if (condition) {body/ consists of codes;} else {}
Else If- several conditions
Switch – testing for several different conditions, num only
Actual Reference: https://en.cppreference.com/w/cpp/io/manip Ternary Operators
std::cout.unset(std::ios::scientific | std::ios::fixed); // hack to unset to Syntax: var = (condition) ? option1 : option2;
default Equivalent to if;else: if(condition) { var = option1; } else {result
=option2;}
Numeric Limits Disadvantage: only 2 options.
#include <limits> - to show the range of how much you can represent Flow Control Summary
a number such as int, float, short int, etc. - If
Std::numeric_limits<numberType::min() or ::max() - Else
Refer: https://en.cppreference.com/w/cpp/types/numeric_limits - Else if
- Switch
Math Functions - Ternary operator
#include <cmath> - library for some math functions
std::floor() – round down Chapter 6: Loops
std::ceil() – round up Loops Introduction
std::abs() – absoulute value Pillars of any loop:
std::cos() – trigonometric functions - Iterator
std::exp(num) – exponential value e = 2.71 raised to num - Starting point,
std::log () - reverse of pow, computes the power of base e in default - Test (controls when the loops stops)
std::pow(base, exponent) – (3, 4) - Increment(decrement)
std::sqrt() – square root - Loop body
std::round() – round the num halfway points For Loop – repetitive task
sytax: for (unsigned int i{}; i < 10; ++i) {codes } Or char message[6] {‘h’, ‘e’, ‘l’, ‘l’, ‘o’}
- This will repeat 10 times Size of an array
Range base for loops Depend on the number of elements.
Syntax: Arrays of characters
int array [] {1, 2, ,3, 4, 5, 6, 7}; STRING LITERAL
for (auto value : array) { Char message [] {“Hello World”};
std:cout << “value : “ << value << std::endl; Array Bounds
} Std::size() – it may be use to know the number of elements the variable
While Loop has. It is useful especially in arrays to know the number of elements being
Syntax: size_t i{0} // declaration of iterator listed. //included in standard library.
while (I < 10) {std::cout<<”print”<<std::endl; ++I;} Chapter 8: Pointers
Do While Loop – runs the body then checks Introduction to Pointers
Pointers – stores the memory address of a variable.
Pointers can only store the same data type of when it is declared.
Pointers size is 8bytes
Declaring and using pointers
Syntax: int* p_number {} ; - recommended than not putting
braces.. this initialize with nullptr
Declaring like this:
Int* p_number, other_num; the first is the only one that is a
Chapter 7: Arrays pointer. Next to it will be an integer variable.
Introduction to Arrays But you can write like int* p_num, *p_num1; this are all
Arrays – set up collection in c++ programs, group of things with a pointers
group name Initializing pointers and assigning them data:
- [] use to denote an array Int int_var{43};
- Example: int scores [10] – group of 10 integers Int* p_int{&int_var} - & before the var is important to avoid
Declaring and using arrays error
- Example: float salaries Dreferencing a pointer – this is to see the data assign in the
- \0 – like return 0 pointer
- FOR char arrays: Syntax : cout << * p_example << endl;
Syntax: char message[6] {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’} Pointer to char
Program Memory Map Revisited
Cpp file Compiler exe file Memory management momory Releasing and Resetting
(MMU) RAM syntax: delete p_var;
Virtual memory – a trick that fools your program into thinking it is p_var = nullptr;
the only program running on your OS, and all memory resources Dangling Pointers
belong to it. Pointers to avoid:
A memory map is a standard format defined by the OS. All 1. Uninitialized – not stated what is the value, this will crash
programs written for that OS must conform to it. It is usually when you dereferenced it.
divided into some sections. 2. Deleted Pointers – when dereference the pointer when it is
SYSTEM just deleted, this will lead to crash.
STACK Local variables, function calls,. 3. Multiple pointers pointing at the same address – avoid doing
HEAP Additional memory that can be because when you delete for example the one pointer the
queried for at run time other pointer that use the same address will crash.
DATA Solutions:
TEXT Binary file o Initialize your pointers
o Reset pointers after delete
Dynamic Memory Allocation o For multiple pointers to same address, make sure the
Allocating memory to be own by our program so we can also use owner pointer is very clear
it later. When new Fails
syntax: int *num{nullptr} In some rare cases, the ‘new" operator will fail to allocate
num = new int; dynamic memory from the heap. When that happens, and you
have no mechanism in place to handle that failure, an exception
will be thrown and your program will crash. BAD!
The exception mechanism
Syntax: for
Std::nothrow – ideal if you dont want exceptions thrown
when new fails // wil throw nullptr if error.
Syntax: int * data = new(std::nothrow) int[100000000];
Null Pointer Safety
To make sure the pointer contains a valid address
You can use this to check if a pointer is nullptr:
Syntax: if(pointer) {cout << “Contains valid address”;} else
{“Invalid”}; // or this:
If (!(pointer == nullptr)) {code} else {code};
Deleting a nullptr pointer is a no problem
Memory Leaks
When we loose access to memory that is dynamically
allocated
Introducing std::string
NOTE: You can create a header file (e.g. header.h) that can be a //when calling
container for your prototype function : (int max(int a, int b);) or int main () {
(int max(int , int );) and you can also put the definition of say_age (age);
function in other cpp file. Remember to include the header.h // the argument that’s going to will be the address since you
(#include “header.h”) in the main cpp file so it will load the put (&) in the paremeter of the say_age function.
function from the header file. return 0;
}
Pass by value
parameter – the passing value in the function.
argument – the passing of value to a function (when calling) Chapter 12: Getting Things out of functions
&varName – using this as a parameter makes the variable Introduction to getting things out of functions
changeable inside and outside the function as this gets the Input and output parameters
address of the variable. Returning from functions by value
Capture lists
Template specialization
struct
it is also like a class but the only difference is struct default
members are public while class default members are private.
Syntax:
struct Cat {
string name;
}
Size of objects