Mastering C++ Operators: Techniques and Best Practices
90 likes | 119 Vues
Learn advanced C++ operators such as assignment expressions, increment and decrement operators, bitwise operators, and how to use cast operations effectively. Understand looping statements and choose the right loop based on your scenario.
Mastering C++ Operators: Techniques and Best Practices
E N D
Presentation Transcript
Additional C++ Operators Robert REaves
Choosing a Looping Statement • Count-controlled loop, use for loop. • Event-controlled loop whose body should execute once, use do-while loop. • Event-controlled loop and nothing is known about the first execution, use while loop. • When in doubt, use a while loop. • Infinite loop, break statements sometimes help.
Additional C++ Operators • P. 323 – 324
Assignment Operators and Assignment Expressions • Assignment Expression is a C++ expression with a value and the side effect of storing the expression value into a memory location. • delta = 2 * 12; • is an expressions, so you can use it anywhere an expression is allowed. • thirdInt = (secondInt = (firstInt = 20) + 10) + 5; • Expression Statement is a statement formed by appending a semicolon to an expression. • 23; • 2 * (alpha + beta)
Increment and Decrement Operators • ++someIntis pre-incrementation • Incrementing occurs before use. • someInt++ is post-incrementation • Use before incrementing occurs.
Bitwise Operators • <<, left shift • >>, right shift • &, bitwise AND • |, bitwise OR • Used for manipulating individual bits within a memory cell.
Cast Operation • Cast operation comes in three forms: • intVar = int(floatVar); // Functional notation • intVar = (int)floatVar; // Prefix notation • intVar = static_cast<int>(floatVar); // Keyword notation • Use explicit type cast to avoid confusing code with implicit type coercion.
Sizeof() • Unary operator that yields the size, in bytes, of its operand. • sizeof(long); • cout << sizeof(int) << endl;
?: Operator • Called the conditional operator, ternary (three-operand) operator. • Expression1? Expression2 : Expression3 • if( a > b) • max = a; • else • max = b; • EQUIVLIENT TO: • max = (a > b) ? a : b;