int a, b; int *p, *q; a = *p *q = 3 b = *p;The compiler would like to store the value of *p into a register and then assign this register value to b, without having to reload *p. However, if q refers to the same object as p, then the register value is no longer valid. Unless the compiler can prove that q and p can never point to the same object, the compiler must reload the value of *p.
class complex { double real, imaginary; ... public: complex operator+(complex &other) { return complex(real + other.real, imaginary + other.imaginary); }; ... complex A, B, C; C = A + B; // treated by C++ as C = A.operator+(B)
string lname = "vander zanden"; string name = "brad" + lname;An example of infix overloading in C++ that handles the above case might be:
string operator+(char *operand1, string operand2) { return string(operand1) + operand2; } int main() { string lname = "vander zanden"; string name = "brad " + lname; }
class person { int age; } int threshold; database people; boolean older_than_threshold(person p) { return p.age >= threshold; } void print_person(person p) { // call appropriate I/O routines to print person on standard output // make use of nonlocal variable line_length to format data in columns } void print_selected_records(database db, procedure predicate, print_routine) { int line_length; if (device_type(stdout) == terminal) line_length = 80 else // standard line length on older printers or files line_length = 132 foreach person p in db do if predicate(p) print_routine(p) } main { threshold = 35; print_selected_records(people, older_than_threshold, print_person); }
def plus_x(x): return def lambda(y): return x+yplus_x returns an unnamed function (lambda functions denote unnamed functions in functional languages and have been adopted by scripting languages such as Python). This unnamed function takes y as a parameter, adds it to x, and returns the sum. The problem is that in a normal imperative language, x is reclaimed once plus_x exits, and hence would be undefined when our unnamed function is called. This problem is referred to as unlimited extent. Local variables with unlimited extent cannot be reclaimed. This in turn means they cannot be allocated on the stack but instead must be allocated on the heap.
interface IntFunc { int call(int i); } class PlusX implements IntFunc { int x; public PlusX(int n) { x = n; } public int call(int i) { return i + x; } } ... IntFunc f = new PlusX(2); System.out.println(f.call(3)); // prints 5The interface defines an abstract type for objects enclosing a function from integers to integers. Whereas Python would capture the value of x in a function closure, Java captures it in an object-closure (also called a function object or functor).