cs31 lecture 3

Example foo x examples int foo 42 19 summary x a

Info icon This 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

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern