Java (C++) Control Abstraction

last modified 1/4/05


Control structures in a high level language

These structured control structures for Java and C/C++

Selection

Iteration

Procedure

if-then (single way decision) while (execute 0 or more times) function call (pass params)
if-then-else (2 way decision) do-while (execute 1 or more times) return (... a value)
switch (multi-way decision) for (execute a known number of iterations)  

 

Control structures found in a machine language

Below are 4 basic instructions in a ML

Jump Jump to subroutine
unconditional branch (goto target) subroutine call (jump-to-subroutine target)
conditional branch (if cond then goto target) return from subroutine (return)
target: [more statements] target: [first statement of module]

 

 

 

 


Early language abstraction

FORTRAN, BASIC and other early languages often mimicked the underlying machine language in regards to control structures
 

Sample FORTRAN code segment Same action in Java 
160 IF (I .LT. J )GOTO 164
       I = I + 3
       PRINT *, I
       GOTO 160
164  K = 5
while (i<j) {
    i = i+3;
    System.out.println( i );
}
k = 5;

With no abstraction of control structures, the code is error prone, and has no logically expressed relationship among the statements. Indentation helps the reading but is not necessary or considered by the computer system.

 

 

 


Advanced Control Structures

Some additional  Java and C++ control statements:

goto  rarely used in C++ (should not be used)
exit  used to terminate a program
return  used to return from function/subroutine 
break  used to exit a loop or switch case but has a well defined destination 
continue used to immediately start the next loop iteration

 

 

 

 


Functional (procedural) abstraction

Subroutines are an abstraction

Some basic reasons for functional abstraction (sub-themes for the course):

Parameters in Java are call-by-value (no ref or & type parameters)

 

 


Functions vs Procedures

As software designers we need to make a distinction between functions and procedures, although the Java or C++ languages do not make that distinction as clear.

Functions are designed to compute a value (or object) to be returned for use typically in a computation. They mimic mathematical functions in that they should NOT produce side effects; instead, functions compute a value or a new object based on the input parameters and simply return it.

Side effects include

Example: In the statement r = sqrt(x); one doesn't expect that x is changed or that the value is printed out

Procedures (void functions in Java/C++) are designed to do a simple task and be named. They tend to have side effects such as input/output or modify a parameter or global variable.