cs31 lecture 3

Example foo x examples int foo 42 19 summary x a

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1; bar = foo + 1 x -- to decrement by 1 and assign the result to the variable Example: foo-- or --foo x - to take the opposite of a value Example: -foo x Examples: int foo = 42; 19 Summary x A variable must be declared before it is used x Declarations can occur (almost) anywhere in the program x Good habit: put all declarations at the beginning x Each instruction ends by ; x Good habit: one instruction per line x Variable names are case-sensitive x Assignment of value can be done at declaration x Be careful to the variable type! 20 Order of evaluation x A common error: making a mistake on the evaluation order Example 1, using G++: Example int n = 2; int int foo = (n + 2) * (++n); // eval: foo = n + 2; n = n + 1; foo = foo * n; // value of foo: 12, value of n: 3 Example 2, using G++: Example int n = 2; int int foo = (n + 2) * (n++); // eval: foo = n + 2; foo = foo * n; n = n + 1; // value of foo: 8, value of n: 3 x Sub-expressions can be evaluated in any order (depends Sub-expressions on the compiler implementation) on 21 n++ versus ++n, using G++ n = 2; m = 2 foo = m + 2 + n++; // the value of n is 2 for the evaluation of foo the expression, after its evaluation it is incremented. foo = 6 the Foo = n++ + 2 + m; // the same, foo = 6 n++ + 2 + n++; // unspecified behavior (C++ standard) ++n + 2 + n; // n is incremented first. foo = 8 (with G++) (++n) + (2 + n) // (2+n) may be evaluated first or second 22 Mixing types x What about using floats and ints in the same expression? Ex...
View Full Document

Ask a homework question - tutors are online