Scope of Declaration §Scope Rule: The scope of a variable starts from its declaration point and extends to the end of the current block in a pair of braces. §Declaration-before-use: Variables and functions must be declared before they are used. { int height = 6; int width = 6; int area = height * width; // . . . } // block ends
Functions and Parameter Passing § A function is a named block of code that must be explicitly called. § The purposes of using functions are twofold: abstraction and reuse: abstraction: statements that form a conceptual unit; reuse: statements that can be executed in more than one place in the program. § Functions communicate with the rest of the program by using either global variables or parameters / return value § Formal and actual parameters. In the declaration formal parameters. When calling a function, actual parameters are given.
Parameter Passing § Call-by-value: a formal parameter is a local variable in the function. It is initialized to the value of the actual parameter. It is a copy of the actual parameter. Advantage: no side-effects (safe, reliable). Drawback: less flexible/less powerful. § Call-by-address (pointer or reference): the formal parameter is a pointer to the actual parameter. There is only one variable with two names. Changing the formal parameter immediately changes the actual parameter. Reference in C++ only. Drawback : side-effects (programmer skills) Advantage: flexible/powerful.
Spring 2018 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.