7 - Control Palooza
ucla | CS 131 | 2023-11-29 15:09
Table of Contents
Expressions, Associativity, and Order of Eval
- C++ is not deterministic in the evaluation of the terms of an expression, e.g. evaluating a function in an arithmetic expression or evaluating a function passed as a parameter

- Instead, it leaves it to the compiler to optimize
- so, we should write pure code that does not introduce possible side effects
- most mathematical expressions are left-associative and are returned in normal mathematical order, but there are some exceptions
- The program will optimize boolean expressions so that it will “short circuit” and only evaluate as few expressions as possible, left-to-right
- short-circuiting is expected but not guaranteed, depends on the lang
Control Statements
Unconditional Branching

GOTO
- assign labels to lines of code
- jump to the label/line
- can introduce undefined behavior if not careful
BREAK and CONTINUE

- new features allow you to break from labeled loops and continue to labeled loops
Conditionals
-
IFwas first used in Fortran to jump to line numbers based on flags for whether the number is negative, zero, or positive - Ternary operator is if else in 1 line w 3 operands
- null coalescing operator: if true then pas s the var else pass alt
- safe navigation operator, checks if the navigation is valid else entire statement is false/null
- started in fortran with a goto and line numbers

Loops

Counter-controlled iteration
- iterates over a range of values (foreach)

Collection-controlled iteration
- iterates over the elements in an iterable objects

Conditional Looping
- while and do while
- do always runs the 1st iteration
Iteration
- Looping/iteration through an iterable object
- these are the types of loops:

Iterable objects
- an iterable object is an object that can be iterated over using an iterator: a collection, list, sequence, range, etc.
- we can iterate using iterators or first class functions

Iterators
- an object that allows the enumeration of an iterable object’s values without exposing the underlying representation

- iterators are typically distinct from the value they enumerate, but to the programmer, it is an abstraction so we can not know if it actually caches or just points
- iterators are distinct from the iterable object so we can have multiple iterators for the same iterable
- iterators are generated by the iterable object and may become invalid over execution (e.g., if you delete an object in a vector in C++, the iterator becomes invalid )


- Iterators are implemented via:

With Traditional Classes:
- Implementing a container:

- Implementing a range:

With Generators (True Iterators)
- A generator in python:
- Iterating through a generator:
First Class Functions for Iteration
- we can create a simple mapping member function that does a for each loop and calls the passed function












