9/9/2012 For Next Time Read Chapter 4 Expressions, and Arithmetic Chapters 4 1 2 Arithmetic Operator Precedence Just as in normal mathematics: Operator Operation * and / are applied before + and – + Addition Parentheses can override the order of application - Subtraction * Multiplication / Division % Modulus 3 Operator Associativity Operator Arity Is x + y + z evaluated as Unary: (x + y) + z -x x + (y + z) +sum Does it matter? Binary sum + diff 2 - ev 1
9/9/2012 Precedence and Associativity Mixed Arithmetic In an expression involving different numeric Precedence from high to low types, the less dominant types are converted to the more dominant types for the purpose of Arity Operators Associativity evaluating the expression +, - Unary Example *, /, % Binary Left int x = 5; +, - Binary Left double y = 4.0, z; = Binary Right z = x + y; Comments Source Code Formatting Helpful to human readers Like comments: unimportant to compiler but very important to human readers Ignored by the compiler Some guidelines: Single-line comments // This is a brief note Each statement on its own line Block comments Align curly braces in a standard way /* This is a longer remark Indent bodies of functions and structured that covers statements several lines. */ Use spaces around binary operators Errors Logic Errors Not detectable by the compiler Compile-time errors Not detectable by the run-time environment Violation of the rules of the C++ language The program’s logic is not correct Compiler tells you about them Plentiful when you are first learning a language The hardest kinds of errors to diagnose and repair The compile can provide no feedback Generally easy to fix Can result from carelessness, lack of understanding of Runtime errors the problem, lack of understanding of the way the Depends on the situation of the running program: like language works; for example: dividing by a variable that has been assigned zero Wrote x - y , meant y - x The run- time environment terminates the program’s execution 2
9/9/2012 Logic Error? Additional Arithmetic Operators Increment: ++ Decrement: -- Increase: += Other operations similar to increase: double degrees_F, degrees_C; -= cin >> degrees_F; *= degrees_C = 5/9*(degrees_F - 32); /= %= Others . . . Next . . . Conditional execution 15 3
Recommend
More recommend