Which of the following is a group of statements which are part of another statement or functions?

C and C++ Programming Language

Kaare Christian, in Encyclopedia of Physical Science and Technology (Third Edition), 2003

II.C Control Structures

In contrast to its eclectic set of operators, C has an unremarkable collection of control structures. One possible exception is the C for loop, which is more compact and flexible than its analogs in other languages. The purpose of the C control structures, like those in other languages, is to provide alternatives to strictly sequential program execution. The control structures make it easy to provide alternate branches, multi-way branches, and repeated execution of parts of a program. (Of course, the most profound control structure is the subroutine, which is discussed in Section II.D.)

A compound statement is simply a group of statements surrounded by curly braces. It can be used anywhere that a simple statement can be used to make a group of statements into a single entity.

for (i=0; i<10; i++) {

x[i] = 0;

y[i] = 0;

z[i] = 0;

}

In the example above, the three assignment statements form a compound statement because they are enclosed in the curly braces. (The for statement will be discussed later in this section.)

The goto statement is the simplest, the oldest, and the most general control statement. Unfortunately, it is also one of the most easily abused statements, and its use is discouraged. It is seldom used by people who write C programs, but it is often used extensively in C programs that are generated by (written by) other programs. In programs written by people, the goto is usually reserved for handling exceptional conditions, such as branching to an error-handling block of code.

The if statement is used to provide alternative execution paths in a program. In an if statement, one of two alternate possibilities is taken, based on the true/false value of a test expression. The syntax is the following.

if (expr)

statement1;

else

statement2;

The else part is optional, and either statement may be a compound statement. (The expression and the statement above are shown in italics, to indicate that they may be any C expression or C statement. The words if and else are keywords, which must appear exactly as shown, which is why they are not shown in italics.) It is very common for the else part of the if statement to contain another if statement, which creates a chain of if-statement tests. This is sometimes called a cascaded if statement:

if (code==10)

statement1;

else if (code < 0)

statement2;

else if (code > 100)

statement3;

else

statement4;

In the series of tests shown here, only one of the four statements will be executed.

An alternative multi-way branch can be created by a C switch statement. In a switch statement, one of several alternatives is executed, depending on the value of a test expression. Each of the alternatives is tagged by a constant value. When the test expression matches one of the constant values, then that alternative is executed.

The syntax of the switch statement is somewhat complicated.

switch (expr) {

case const1:

statement1;

break;

case const2:

statement2;

break;

default:

statement3;

break;

}

In this skeleton switch statement, expr is the test expression and const1 and const2 symbolize the constants that identify the alternatives. In this example, each alternative is shown terminated by a break statement, which is common but not required. Without these break statements, flow of control would meander from the end of each alternative into the beginning of the following. This behavior is not usually what the programmer wants, but it is one of the possibilities that is present in C's switch statement. The break statement will be discussed further later.

The switch statement is less general than the cascaded if statement, because in a cascaded if statement each alternative can be associated with a complex expression, while in a switch statement each alternative is associated with a constant value (or with several constant values; multiple case labels are allowed).

The switch statement has two advantages over the more flexible cascaded if statement. The first is clarity; when a solution can be expressed by a switch statement, then that solution is probably the clearest solution. The second is efficiency. In a cascaded if statement, each test expression must be evaluated in turn until one of the expressions is true. In a switch statement, it is often possible for the C compiler to generate code that branches directly to the target case.

A while loop lets you repeatedly execute a statement (or group of statements) while some condition is true. It is the simplest iterative statement in C, but it is also very general.

while (ch != EOF)

statement;

The body of this loop (the statement) will be executed repeatedly until the value of the ch variable becomes equal to the value of the standard predefined constant EOF (end of file). Presumably, something in the statement will alter the value of ch so the loop will end. Also, it is presumed that ch is assigned a value prior to the execution of the while statement. (Note that the statement will not be executed if the initial value of ch is EOF.)

It is easy to use a while loop to step through a series of values. For example, the following while loop zeroes the first ten elements of an array named x. (An integer variable named i is used as the array index and as the loop counter.)

i = 0;

while (i < 10) {

x[i++] = 0;

}

A close relative of the while loop is C's do loop. It repeats a statement (or a group of statements) while a condition is true, but the condition is tested at the bottom of the loop, not at the top of the loop. This ensures that the body of the loop will always be executed at least once.

i = 0;

do

x[i] = 0;

while (++i < 10);

As with a while loop, something in the body of the loop or the control expression presumably changes the value of the test expression, so that the loop will eventually terminate.

C's most elaborate loop is the for loop. Here is the general form of the for loop:

for (init_expr; test_expr; inc_expr)

statement;

As in the previous examples, the statement will be repeatedly executed, based on the values of the three control expressions. The init_expr is an initialization expression. It is executed just once—before the body of the loop starts to execute. The test_expr is executed before each iteration of the loop. If it is true, the next iteration will occur, otherwise the loop will be terminated. The inc_expr is executed at the conclusion of every iteration, typically to increment a loop counter.

Here is a typical for loop. It performs the same task as before, setting the first ten elements of an array named x to zero, using a loop counter named i:

for (i=0; i<l0; i++)

x[i] = 0;

Note that the while version of this loop was four lines, while the for version of the loop is just two. This for loop is an example of what Kernighan and Ritchie, authors of the seminal reference book on C, call “economy of expression,” which is one of C's most distinctive traits.

C has two additional flow of control statements, break and continue, that augment the capabilities of the loops that have just been described. The break statement is used to break out of (to immediately terminate) the enclosing do, while, for, or switch statement. Its use is routine in switch statements, to terminate the switch statement at the conclusion of each individual case. In do, while, and for loops, break is often used to terminate the loop prematurely when an error or special condition occurs. Using a break in the body of a loop often simplifies the control expression of the loop, because it allows special case code to be placed elsewhere.

The continue statement is used to immediately start the next iteration of the surrounding do, while, or for loop. It is somewhat like a jump to the end of a loop. For example, suppose a program is reading a list of words from a file. Certain processing must occur for most words, but a few words are just ignored. Here is a pseudocode sketch (pseudocode isn't true C; it merely expresses an idea without following strict syntax) of how that could be written using the continue statement.

while (readaword ()) {

if (word is in the ignore list)

continue;

process a word;

The effect of the continue statement is to skip the process a word part of the loop body for words that are in the ignore list.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B0122274105008395

Lectures on the Curry-Howard Isomorphism

Morten Heine Sørensen, Pawel Urzyczyin, in Studies in Logic and the Foundations of Mathematics, 2006

The objects investigated by propositional logic are compound statements, built from some atomic statements (represented by propositional variables) by means of logical connectives. The objective is to understand relations between compound statements, depending on their structure, rather than on the actual “meaning” of the atoms occurring in these statements. For instance, one does not have to read [219] to assert the (constructive) correctness of the following reasoning by means of the propositional calculus.

If Yossarian is not insane then he will not be relieved of flying missions.

If Yossarian is insane then he will not be relieved of flying missions.

Therefore Yossarian will not be relieved of flying missions.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/S0049237X06800091

Concurrency

Michael L. Scott, in Programming Language Pragmatics (Third Edition), 2009

Co-begin

Example 12.6

General form of co-begin

The usual semantics of a compound statement (sometimes delimited with begin…end) call for sequential execution of the constituent statements. A co-begin construct calls instead for concurrent execution:

co-begin --all n statements run concurrently

 stmt_1

 stmt_2

 …

 stmt_n

end

Each statement can itself be a sequential or parallel compound, or (commonly) a subroutine call.

Example 12.7

Co-begin in OpenMP

Co-begin was the principal means of creating threads in Algol-68. It appears in a variety of other systems as well, including OpenMP:

#pragma omp sections

{

# pragma omp section

 { printf("thread 1 here\n"); }

# pragma omp section

 { printf("thread 2 here\n"); }

}

In C, OpenMP directives all begin with #pragma omp. (The # sign must appear in column 1.) Most directives, like those shown here, must appear immediately before a loop construct or a compound statement delimited with curly braces.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780123745149000082

Fork–Join

Michael McCool, ... James Reinders, in Structured Parallel Programming, 2012

8.2.3 OpenMP Support for Fork–Join

OpenMP 3.0 also has a fork–join construct. Here is an OpenMP fragment for the fork–join control flow from Figure 8.1:

#pragma omp task

B();

C();

#pragma omp taskwait

The construct task indicates that the subsequent statement can be independently scheduled as a task. In the example, the statement “B();” is run in parallel. The statement could also be a compound statement—that is, a group of statements surrounded by braces. The work in C() is performed by the spawning task, and finally the construct omp taskwait waits for all child tasks of the current task.

There is a catch peculiar to OpenMP: Parallelism happens only inside parallel regions. Thus, for the example to actually fork there must be an enclosing OpenMP parallel construct, either in the current routine or further up the call chain.

Variable capture needs attention. OpenMP tasks essentially capture global variables by reference and local variables by value. In OpenMP parlance, these capture modes are respectively called shared and firstprivate. Sometimes these defaults must be overridden, as the following fragment illustrates:

int foo( int i ) {

 int x, y;

#pragma omp task shared(x)

 x = f(i);

 ++i;

 y = g(i);

#pragma omp taskwait

 return x+y;

}

The shared clause requests that x be captured by reference. Without it, x would be captured by value, and the effect of the assignment x = f(i) would be lost.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780124159938000086

Patterns

Michael McCool, ... James Reinders, in Structured Parallel Programming, 2012

3.3.1 Fork–Join

The fork–join pattern lets control flow fork into multiple parallel flows that rejoin later. Various parallel frameworks abstract fork–join in different ways. Some treat fork–join as a parallel form of a compound statement; instead of executing substatements one after the other, they are executed in parallel. Some like OpenMP's parallel region fork control into multiple threads that all execute the same statement and use other constructs to determine which thread does what.

Another approach, used in Cilk Plus, generalizes serial call trees to parallel call trees, by letting code spawn a function instead of calling it. A spawned call is like a normal call, except the caller can keep going without waiting for the callee to return, hence forking control flow between caller and callee. The caller later executes a join operation (called “sync” in Cilk Plus) to wait for the callee to return, thus merging the control flow. This approach can be implemented with an efficient mechanism that extends the stack-oriented call/return mechanism used for serial function calls.

Fork–join should not be confused with barriers. A barrier is a synchronization construct across multiple threads. In a barrier, each thread must wait for all other threads to reach the barrier before any of them leave. The difference is that after a barrier all threads continue, but after a join only one does. Sometimes barriers are used to imitate joins, by making all threads execute identical code after the barrier, until the next conceptual fork.

The fork–join pattern in Cilk Plus is structured in that the task graph generated is cleanly nested and planar, so the program can be reasoned about in a hierarchical fashion. When we refer to the fork–join pattern in this book we will be specifically referring to this structured form.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780124159938000037

The Way of the Engineer

Robert Charles Metzger, in Debugging by Thinking, 2004

13.5.2.12 Statement convention examples

Listed as follows is a set of conventions for C++ that address the issues of statement structure. There are other choices that are reasonable and effective in preventing bugs.

Do indent four spaces for nested control-flow constructs.

Do indent four spaces for nested class members.

Do split lines that run over eighty characters:

Break after a comma.

Break before an operator.

Indent eight spaces from the left edge of the beginning of the statement.

Do put opening braces on the same line as the keyword they're associated with.

Do put closing braces on a separate line, indented to the same level as the associate keyword.

Do follow the if, else, while, for, and do keywords with a compound statement block, rather than a simple statement, even if the block contains only one or even zero statements.

Don't put spaces around the reference operators “.” and “->” or between unary operators and their operands.

Do put spaces between binary operators and their operands.

Do conclude the code after a case statement with a break statement.

Do include a default case in a switch statement.

Avoid using do while loops.

Do put each simple statement on a separate line.

Don't assign more than one variable in a statement.

Do parenthesize expressions with more than one operator, so that the default precedence rules are made plain.

Listed as follows is a set of conventions for Java that address the issues of statement structure. There are other choices that are reasonable and effective in preventing bugs.

Do split lines that run over eighty characters:

Break after a comma.

Break before an operator.

Break after a parenthesis.

Do indent one tab stop for nested control constructs.

Do indent one tab stop for nested class members.

Do put an open brace on the same line as the declaration statement.

Do put a closing brace on a separate line, indented to the same level as the first keyword of the declaration statement.

Do put each simple statement on a separate line.

Don't put extra parentheses in a return statement.

Do indent statements in a compound statement one level.

Do put braces around the statements of a compound statement, even if there is only one statement in the block.

Do put an open brace on the same line as a control-flow statement.

Do put a closing brace on a separate line, indented to the same level as the first keyword of the control-flow statement.

Do put case statements at the same level of indentation as the switch statement that controls them.

Do indent the statements of a case one level.

Either put a break statement or a comment that the case falls through at the end of every case.

Don't assign more than one variable in an assignment statement.

Do parenthesize the first operand of the ternary conditional operator.

Do put a blank space after keywords that are followed by parentheses (while, if, for, switch).

Do put a blank space after commas in argument lists.

Do put a blank space between binary operators and their operands, except for the dot operator.

Do put a blank space after semicolons in compound statements.

Do put a blank space after cast operators.

Avoid using do while loops.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9781555583071500136

Problem solving and the art of the convincing argument

Mary Attenborough, in Mathematics for Electrical Engineering and Computing, 2003

Example 3.4

Assign truth values to the following:

(a)

x−2=3∧x2=4whenx=2

(b)

x−2=3∨x2=4whenx=2

(c)

¬ (x−4=0)whenx=4

(d)

¬(( a−b)=4)∨(a+b)=2when a=5, b=3

Solution

(a)

x − 2 = 3 ∧ x2= 4 when x = 2

Substitute x = 2 into the predicate, x − 2 = 3 ∧ x2 = 4 and we get 2 − 3 = 3 ∧ 22 = 4.

The first part of the compound statement is false and the second part is true. Overall, as F ∧ T ⇔ F, the proposition is false.

(b)

x – 2 = 3 ∨ x2 = 4 when x = 2

Substitute x = 2 into the predicate and we get

2 − 2 = 3 ∨ 22 = 4

The first part of the compound statement is false and second part is true. As F ∨ T ⇔ T, the proposition is true.

(c)

¬(x − 4 = 0) when x = 4

When x = 4 the expression becomes:

¬(4−4=0)⇔¬T⇔F

(d)

¬((a−b)=4)∨(a+b)=2 whena=5,b=3¬((a−b)=4)whena=5,b=3gives¬(5−3=4)⇔¬F⇔T(a+b)=2whena=5,b=3gives(5+3)=2⇔8=2⇔F

Overall, T ∨ F ⇔ T so ¬ ((a –b) = 4) ∨ (a + b) = 2 when a = 5, b = 3 is true.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780750658553500292

The Way of the Psychologist

Robert Charles Metzger, in Debugging by Thinking, 2004

12.5.2.2 Interrupt sequence, omit step

Reason refers to these types of errors as omissions following interruptions, while Silverman refers to them as omissions due to interruptions.

These errors occur when the majority of your attention resources is claimed by internal or external distraction at a critical point in the execution of a sequence of actions. When your attention returns to executing the sequence, you omit one or more steps from the sequence and continue on. These errors are more likely if you performed some action that will be treated as a substitute for the next step of the sequence.

The following is a programming example of this type of error. Coding switch compound statements in C++ and Java involves a double set of repetitions. The construct as a whole requires the switch keyword, an opening brace, a sequence of case statements, and a closing brace. Within a given case, you must provide the case keyword, an integer value followed by a semicolon, a block of one or more statements, and a break statement.

It is very easy to lose your place in a nested set of repetitions. It is easy to be distracted by some event on your computer, such as a task running in the background, which suddenly pops up a window. If this happens, you may unconsciously substitute the response to that window as the next action you should have taken in composing the switch statement. This may cause you to omit an entire case, or even more unfortunately, omit the break statement. In either case, your switch will be syntactically correct and won't be rejected by the compiler.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9781555583071500124

Embedded SQL, CLI Dynamic SQL, and SQL/PSM

Joe Celko, in Joe Celko's SQL for Smarties (Fifth Edition), 2015

38.4 SQL/PSM History

SQL/PSM (SQL/Persistent Stored Modules) is an ISO standard mainly defining an extension of SQL with a procedural language for use in stored procedures. This was the work of Andrew Eisenberg of DEC (Digital Equipment Corporation), who was impressed with ADA. Younger readers will not remember DEC or the ADA language and the Department of Defense ADA initiative. The first version was published in 1996 as an extension of SQL-92. Later, SQL followed the COBOL Standard model of separate modules for optional facilities to use with the SQL standard.

It is a block structured language that uses the ADA model; a block has the usual scoping rules. Local variables are declared at the start of a block, the executable cod is in the body and the “condition handling” (error handling) is at the end of the block. The syntax has control flow with the classic if-then-else family, loops, and error signaling. There are also local variables, assignment of expressions to variables and parameters, and (procedural) use of cursors. It also defines an information schema (metadata) for stored procedures.

In practice, you will find SQL venders who have had their own procedural languages which are block structured. Some vendors later added a SQL/PSM dialect, but cannot get rid of their old proprietary languages. This is called the “code museum effect” where the customer base has too much invested in it. Some examples are as follows: MySQL uses only the SQL/PSM procedure headers, but no control flow at all; IBM has a SQL/PSM in DB2; Mimer has a SQL/PSM implementation, and Oracle’s PL/SQL is a SQL/PSM dialect. Informix/SPL is more Algol-like and the T-SQL language in MS SQL Server is a mix of Algol and C. A PostgreSQL add-on implements SQL/PSM (alongside its own procedural language), although it is not part of the core product.

38.4.1 SQL Statements

It should be obvious that we can use pretty much any SQL statement in SQL/PSM that makes sense. You cannot generally create schema objects and have to use the existing schema. Declarations are placed at the start of a block, so that variables, conditions, etc. will exist before they are used in the block. They also disappear when the program exits the block.

Variables are easy to understand and use the standard SQL data types. This is like any other programming language. Declaring SQL conditions and handlers is a bit strange. It might be easier to show with an example:

DECLARE overflow CONDITION FOR SQLSTATE ‘22003’;

DECLARE EXIT HANDLER FOR overflow;

The first declaration gives a name the SQLSTATE code for a mathematical overflow to make the code easier to read. But you will probably use one of these three built-in condition names:

NOT FOUND

Identifies any condition that results in an SQLCODE of + 100 or an SQLSTATE beginning with the characters ‘02’.

SQLEXCEPTION

Identifies any condition that results in a negative SQLCODE.

SQLWARNING

Identifies any condition that results in a warning condition, or that results in a positive SQL return code other than + 100. The corresponding SQLSTATE value will begin with the characters ‘01’. The old SQLCODE is still supported in many SQL products. It is a numeric code that has been replaced by the five-character SQLSTATE. Negative SQLCODE values are fatal errors, zero is normal execution, and positive numbers are warnings.

CONTINUE

Specifies that after the procedure statement completes, execution continues with the statement after the statement that caused the error.

EXIT

Specifies that after the procedure statement completes, execution continues at the end of the compound statement that contains the handler.

UNDO

Specifies that before the procedure statement executes, SQL rolls back any SQL operations that have occurred in the compound statement that contains the handler. After the procedure statement completes, execution continues at the end of the compound statement that contains the handler. You can only declare UNDO handlers in ATOMIC compound statements. This is like a ROLLBACK in a transaction.

You should declare separate HANDLER statements to handle specific SQL errors, but declare a generalized HANDLER FOR SQLEXCEPTION and SQLWARNING at the outermost compound statement. Be careful coding CONTINUE HANDLER declarations; you can keep bad data.

You can retrieve diagnostic information using the GET DIAGNOSTICS statement; I am not discussing it here.

38.4.2 Compound Statements

This language uses two versions of the begin-end pair found in other languages. The syntax is

[< label >:] BEGIN [NOT [ATOMIC]] < SQL/PSM statements > END < label >;

The < label > is an optional name for the block and that name can be used in error messages. The tricky part is the “begin atomic” option. This makes the enclosed statements into a single unit of work, like transaction. ATOMIC blocks cannot have COMMIT or ROLLBACK statements and the only handler allowed is UNDO. While redundant, the NOT ATOMIC option is allowed and it is the default if nothing is given.

38.4.3 SIGNAL and RESIGNAL Statements

You use the SIGNAL and RESIGNAL statements to explicitly raise a specific SQLSTATE. The SET MESSAGE_TEXT clause gives the text displayed with the SQLSTATE. Since we can add custom SQL STATE codes, they can only be signaled this way.

Again, it is easier to show an example:

DECLARE EXIT HANDLER FOR SQLSTATE '72822';

BEGIN

IF (silly_flg = 'OK')

THEN RESIGNAL SQLSTATE '72623'

SET MESSAGE_TEXT = 'signaled SQLSTATE 72822';

ELSE RESIGNAL SQLSTATE '72319'

SET MESSAGE_TEXT = silly_flg;

END IF;

END;

SIGNAL SQLSTATE '72822';

This fragment declares a condition handler for the custom SQLSTATE 72822. When the SQL procedure executes the SIGNAL statement that raises SQLSTATE 72822, SQL invokes the condition handler. The condition handler tests the value of the SQL variable silly_flg with an IF statement. If silly_flg = ‘OK’, the handler redefines the SQLSTATE value as 72623 and assigns a string literal to the text associated with SQLSTATE 72623. If silly_flg <> ‘OK’ then the handler redefines the SQLSTATE value as 72319 and assigns the value of the string silly_flg to the text associated with that SQLSTATE.

38.4.4 Assignment Statements

The keyword SET is used in the UPDATE statement to change the values in a column. But it is also used to change schema level parameters like constraints (DEFERRED or IMMEDIATE), time zone, TRANSACTION ISOLATION LEVEL, etc.

Change connection parameters, such as the user name or the time zone or the default schema. In SQL/PSM we will tend to use it for assigning a value for variable.

SET < variable name > = < expression >;

38.4.5 Conditional Statements

There are two forms of conditional execution statements, the IF and the CASE. The syntax for the simple IF statement is the same as other languages.

IF < conditional expression >

THEN < statement list >

[ELSE < statement list >] END IF;

If the conditional expression yields TRUE, the statement in the THEN clause is executed. If the conditional expression tests to FALSE or UNKNOWN, then the ELSE clause is executed.

One or more IF statements can be nested, one within the other, by using an ELSEIF clause in place of the ELSE clause in the IF statement containing another.

IF < conditional expression >

THEN < statement list >

ELSEIF < conditional expression >

THEN < statement list >

ELSE < statement list >

END IF;

Once the SQL statements to be executed have been selected, they execute in the same way as any ordinary list of SQL statements. This is important when creating handlers.

Examples:

IF a > 50 THEN

SET a = 50;

SET b = 1;

ELSE

SET b = 0;

END IF;

IF a > 50 THEN

SET a = 50;

SET b = 2;

ELSEIF a > 25

THEN SET b = 1;

ELSE SET b = 0;

END IF;

SQL/PSM has a CASE statement, which is not to be confused with the CASE expression in SQL. The simple CASE statement looks like the simple CASE expression with statement lists instead of scalar expressions in the THEN and ELSE clauses. Another difference is that it ends with END CASE, to keep the ADA-style statement terminators

A simple CASE works by evaluating equality between one value expression and one or more alternatives of a second value expression. For example:

BEGIN

DECLARE b INTEGER;

CASE b

WHEN 1 THEN UPDATE Foobar SET x = 1;

WHEN 2 THEN UPDATE Foobar SET x = 2;

WHEN 3 THEN UPDATE Foobar SET x = 3;

ELSE UPDATE Foobar SET x = 4;

END CASE;

END;

Like wise the searched CASE statement works the same way.

A searched CASE works by evaluating, for truth, a number of alternative search conditions. For example:

CASE

WHEN EXISTS (SELECT * FROM BILL)

THEN UPDATE Foobar SET x = 1;

WHEN a > 0 OR b = 1

THEN UPDATE Foobar SET x = a + b;

ELSE UPDATE Foobar SET x = -99;

END CASE;

A list of one or more SQL statements can follow the THEN clause for each of the conditional statements. Each alternative list of SQL statements in a CASE statement is treated in the same way, with respect to the behavior of exception handlers and so forth. They are not considered, in any sense, to be a single statement.

The conditional part of each WHEN clause is evaluated, working from the top of the CASE statement down. The SQL statements that are actually executed are those following the THEN clause of the first WHEN condition to evaluate to TRUE. If none of the WHEN conditions evaluate to TRUE, the SQL statements following the CASE statement ELSE clause are executed.

The presence of an ELSE clause in the CASE statement is optional and if it is not present (and none of the WHEN conditions evaluate to TRUE) an exception condition is raised to indicate that a WHEN or ELSE clause was not found for the CASE statement. If you do not want this exception, use an empty statement—ELSE BEGIN END.

38.4.6 Loops

SQL/PSM went crazy with looping constructs. If you are old enough to remember the Structured Programming Revolution of the 1970s, we started with the simple WHILE or pre-test loop, from, Algol and then added the REPEAT or post-test.

The LOOP statement contains a list of one or more SQL statements that are executed, in order, repeatedly. By itself, it is endless, but you can terminate it with the LEAVE statement, or if an exception condition is raised. You need to put label on the LOOP to use the LEAVE. Again, an example is easier to see.

Example:

[< label >:] LOOP

< statement list >

IF < conditional expression > LEAVE < label >;

< statement list >

END LOOP [< label >];

Obviously you can write a pre-test or post-test loop with this or a more general loop that exits at any desired point in the execution. SQL/PSM has the classic pre- and post-test loops, while and repeat.

The WHILE loop may be preceded by a label that can be used as an argument to LEAVE in order to terminate the while loop. The WHILE statement can contain a list of one or more SQL statements that are executed, repeatedly until the condition expression is FALSE. This also means that it can be executed zero times if the condition is false at the start.

[< label >:] WHILE < conditional expression >

< statement list >

END WHILE [< label >];

The REPEAT statement includes an UNTIL clause, which specifies a conditional expression, and iteration continues until this expression evaluates to TRUE. Iteration may also be terminated by executing the LEAVE statement, or if an exception condition is raised.

[< label >:] REPEAT

< statement list >;

UNTIL < conditional expression >

END REPEAT [< label >];

The ITERATE statement can be used to skip statements. It says go back to the start of the labeled looping statement which contains it. If you have nested labeled statements, control will jump to the label on that statement without regard to the nesting levels.

38.4.7 PRINT Statement

This one explains itself. It is not fancy and does no detailed display formatting. It is used to pass a message to the programmer.

38.4.8 CALL Statements

This keyword is taken from FORTRAN! The argument values given to the parameters in the list are in the same order as the procedure declaration.

CALL < procedure name > ([< parameter list >])

The argument data type has to be cast to the parameter data type.

38.4.9 CREATE PROCEDURE and CREATE FUNCTION

This is the important stuff. The syntax for the header is partially ADA and features unique to SQL/PSM. The header tells the compiler more information than previous languages.

The SQL/PSM can tell the compiler if the body is in one of the supported ANSI/ISO Standard languages (FORTRAN, COBOL, C, ADA, etc.) with SQL interfaces defined for them. This is part of the ADA heritage in a weird way. I worked with ADA when it was first created and we found it to be unusable for embedded systems. We did “hag fish” programming; this is a horrible technique where you put an ADA wrapper around the real program to meet a legal requirement. For us, this was usually in C, Assembly, or FORTH which are languages suited for designed for embedded systems.

The header tells the compiler if the function or procedure is or is not deterministic. A deterministic code module always produces the same result when invoked with the same parameters. This is important for an optimizer to know in a functional or declarative language. The optimizer can build a look-up table during execution and use it without recomputing the function or procedure over and over.

The header has three different options for the routine access clause (CONTAINS SQL, READS SQL DATA, and MODIFIES SQL DATA), so the optimizer knows how to set up storage and access control.

The parameter list is made of column names that are unique within the scope of the routine body. Each parameter has an optional mode specification (IN, OUT, or INOUT). When the mode is not explicitly specified, IN is assumed. This is a solution to how parameters are passed which was a hot topic when Algol-60 was new. The old system had a “call by value” which says that the parameter is evaluated and that value is assigned to a local variable in the scope of the routine. The parameter could be an expression in this model. In contrast, there is “call by name” where the parameter is an expression that is plugged directly into the body of the routine. You can get a good overview at http://en.wikipedia.org/wiki/Evaluation_strategy.

In the SQL/PSM model, each parameter has a local variable in the scope of the procedure. Each parameter of a procedure can have an optional mode specification (IN, OUT, or INOUT). These are defined as:

IN

The parameter is effectively read-only, that is, it cannot be used as the target in an assignment, fetch or select into statement in the procedure.

OUT

The parameter is effectively write-only, that is, it can only be used as the target for an assignment and cannot be used in a value expression in the procedure. This type of parameter must be a variable in the procedure CALL statement.

INOUT

The parameter can be used as both an IN and an OUT parameter; this type of parameter must be a variable in the procedure CALL statement.

If no mode is given then IN is implicit. All the parameters in a function have to be IN mode.

The RETURN statement jumps out of the whole routine and control goes to the containing environment. A function has to use a “RETURN < scalar value>” statement in the body which gives the function its value as it leaves.

There are two major idioms in SQL/PSM.

1.

The body of the routine is pure declarative SQL. This is used to encapsulate SQL that might have been submitted via a tool.

2.

The body of the routine is a cursor that is used like a sequential file. This is popular with Oracle programmers who tend to use their PL/SQL as an application development language. This is so common; SQL/PSM has a syntax to simplify the usual cursor coding.

FOR-DO Loop

In other languages, a for-loop is a counting construct that increments a local variable whose values are used in a sequence within the scope of the loop body. But in SQL/PSM, a FOR statement iterates through all rows in a result set and performs some operations for each row. This is a vast simplification compared to using a cursor. Again, easier to show an example.

FOR SELECT last_name, first_name

FROM Customers

WHERE customer_id IN

(SELECT customer_id

FROM Orders

WHERE order_date

BETWEEN DATE '2018-01-01' AND DATE '2018-06-31')

DO CALL Classify_Name(last_name, first_name);

END FOR;

The FOR clause executes a SELECT statement to create a result set. Within the body of the FOR statement it is possible to reference the columns’ values as ordinary variables. This also means that each item in the SELECT list must have a name and that name must be unique within the SELECT list.

The statement in the DO clause has to be an atomic statement. It is possible to use a result procedure in a FOR statement.

FOR CALL coming_soon('Blues')

DO IF producer IN ('Bill Vernon', 'Bill Ham')

THEN INSERT INTO stats(format, release_date, …)

VALUES (format, release_date, …);

END IF;

END FOR;

In this case, the correlation names for the result set and its columns in the AS clause can be used as variable names in the body of the FOR statement.

The SELECT or call statement in the FOR statement can be labeled and this label can be used to qualify variable references.

L1: BEGIN

DECLARE first_name CHAR(12);

SET first_name = 'Joe';

FOR R1

AS SELECT C1.last_name

FROM Customers AS C1

DO IF L1.first_name <> R1.first_name

THEN

..

END IF;

END FOR;

END; 

The label used cannot be the same as any label of a compound statement enclosing the FOR statement.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780128007617000383

The Relational Paradigm

Tom Johnston, in Bitemporal Data, 2014

Rules of Inference

The other component are the deductively valid arguments that can be constructed in the logic. An argument is the derivation of a statement from one or more other statements – equivalently, the derivation of one wff from one or more other wffs. The derived statement/wff is the conclusion of the argument; the statements/wffs it is derived from are the premises of that argument.

The supreme responsibility which any system of deductive logic has is to never permit a false conclusion to be derived from true premises. This means that from a set of statements that are true, all other statements derived by means of transformation rules or inference rules will also be true.

The following are some rules of inference used in many systems of propositional logic. All of them fulfill this responsibility, as do the transformation rules listed in Figure 4.6. These inference rules permit us to add a statement to the set of statements consisting of the premises of the argument and any previously derived statements.8

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.8. Rule of Simplification.

The semantics of this rule is that if we know that both X and Y are true, then we can be sure that X is true. The syntax of this rule (expressed as a function in a string manipulation program, for example) is that if we have (X∧Y) as one line of an argument, then we can write down X as a new line.

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.9. Rule of Conjunction.

The rule of conjunction says that from X and Y, we can derive (X∧Y).9 So if a string manipulation program that includes this rule finds two lines, one X and the other Y, it can generate a new line (X∧Y). Since this rule could be applied by a program to any conjunction, no matter how complex the conjunction and how complex any of its conjuncts, then although the rule itself may seem trivially obvious, it can still be a very useful rule.

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.10. Rule of Addition.

The rule of addition says that from X, we can derive (X∨Y). For example, if it’s true that water only flows downhill, then it’s also true that either water only flows downhill or the sun is 10 million miles from the earth. (There is no requirement that an added disjunct be a true statement.)10

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.11. Rule of Modus Ponens.

The rule of modus ponens says that from (X→Y), and also X, we can derive Y. This is the most widely-used rule of inference in propositional logic. From the truth table for (X→Y), we know that the one and only case in which (X→Y) is false is the case where X is true and Y is false. Since our premises are that (X→Y) is true, and that X is also true, we know that Y cannot be false.

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.12. Rule of Modus Tollens.

The rule of modus tollens says that from (X→Y) and ~Y, we can derive ~X. It is the corollary of modus ponens. From the truth table for (X→Y), we know that the one and only case in which (X→Y) is false is the case where X is true and Y is false. Since our premises are that (X→Y) and ~Y are both true, we know that X cannot be true.

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.13. Rule of Chain Deduction.

The rule of chain deduction expresses the transitivity of material implication. It says that from (X→Y) and (Y→Z), we can derive (X→Z).

Which of the following is a group of statements which are part of another statement or functions?

Figure 4.14. Rule of Disjunctive Simplification.

The rule of disjunctive simplification says that from (X∨Y), and ~X, we can derive Y. For example, if it’s true that either Mike or Steve went to Harvard, and also that Mike went to Stanford (in other words, that Mike didn’t go to Harvard), then it follows that it’s Steve who went to Harvard.

Usually, systems of propositional logic use only a few rules of inference. It is interesting to note that none of the rules of inference for material implication are necessary. Since (X→Y) is equivalent to (~X∨Y), we can transform any statement containing (X→Y) into a statement containing (~X∨Y). In particular, the full functionality of propositional logic is possible in a system in which only conjunction, disjunction and negation are used to form statements – a system such as SQL, for example. In such a system, the only rules of inference that would apply are those that warrant the derivation of a statement from one or more other statements when all compound statements are expressed with the connectives “∧”, “∨” and “~”, and with no other connectives.

Read full chapter

URL: https://www.sciencedirect.com/science/article/pii/B9780124080676000048

Which of the following is a group of statements which are part of another statement or functions in Python?

Function is a group of statements that performs specific task. It runs only when it is called. You can pass data (parameters) into a function.

Which of the following is a group of statements which are part of another statement?

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.

What is a group of statements called?

An argument is a group of statements including one or more premises and one and only one conclusion.

What are the 3 types of program statements?

A statement forms a complete unit of execution and is terminated with a semicolon ( ; ). There are three kinds of statements: expression statements, declaration statements, and control flow statements.