Elements of an Imperative-Based Programming Language

  1. Comments

Rule for writing valid comments

Example:

In C++ a comment is any sequence of character between the characters /* and */

For example:/*------A Sample Program ------*/

Or any sequence of characters that follows the characters // and that ends at the end of the line.

For example:// to hold an integer value

  1. Identifiers

Rules for writing valid identifiers

Length of an identifier

Case sensitivity: are uppercase and lowercase characters different?

Connectors

Examples: underscore in C/C++ and Java; dash character in COBOL

Pascal, Modula-2, and FORTRAN 77 do not allow connectors

Keywordsare words with assigned meanings in certain contexts.

Examples:if, while, else in C/C++.

Reserved wordsare words that cannot be used as user-defined names

In C/C++ all keywords are reserved words

In FORTRAN, keywords integer and real are not reserved words

For example, REAL and INTEGER are keywords, which are not reserved words:

INTEGER REAL

REAL INTEGER

In Ada, keywords integer and float are not reserved words.

Standard identifiers:

-Are names that are defined in libraries and/or other program units and made visible to programmers in C/C++, Ada, and Java.

-These names can be redefined by the programmer.

Examples, printf, and scanf in C.

Constant Data/ Literal Constants

  • Are the data that may be specified in the text of a program.
  • Possible constant data follow:

Boolean constants

Character constants

Integer constants

Decimal constants

Floating-point constants

String constants

Special constants

  1. Variables

In an imperative language, a variable is an abstraction of a memory cell.

The following are the fundamental semantic issues of variables in an imperative language:

  1. Attribute of variables.
  2. Issues of aliases.
  3. Binding and binding times for variable attributes
  4. Classification of variables into categories (according to their binding times).
  5. Type checking, strong typing, and type compatibility rules.
  6. Scoping rules for names: static and dynamic.
  7. Referencing environment of a statement.
  8. Named constants and variable initialization techniques.

Attributes of Variables

In an imperative language, a variable is characterized by the following attributes:

  1. Name:how is it referred to?
  2. Address:where is the corresponding memory cell located in memory?
  3. Value:what is the value stored at the corresponding memory location?
  4. Type:what is the type of values that can be stored at the corresponding memory location?
  5. Lifetime:for how long does the corresponding memory cell is kept in memory?
  6. Scope:where in the program can a reference be made to the variable?

Name of a Variable

For example, in C++ and Java, the name of a variable is an identifier.

Address of a variable

The address of a variable is the address of the corresponding memory cell.

It is sometimes referred to as the l-value of the variable whereas it contents is referred to as its r-value.

Examplenum = num + 5;

l-value r-value

The address of a variable is accessible in C++ but not in Java.

You access the address of a variable in C++ by using the address of operator &

For example if num is the name of a variable, then its address is specified as: &num.

Type

The type of a variable determines the range of values of that variable and the set of operations that are defined for those values.

In the case of floating-point, it also determines the precision.

Value

The value of a variable is the contents of the memory location associated to that variable.

It is also called the r-value of the variable.

  1. Primitive Data Types and Type Binding

Signed integersare represented in two’s complement.

Data types:C/C++/C#Java

signed charbyte

short intshort

intint

long intlong

Unsigned integersare represented as sequences of bits.

C/C++/C#Java

char (1 byte) char (2 bytes)also used to represent a single character

unsigned char

unsigned short int

unsigned int

unsigned long int

Floating-point Types

-are used to approximate real numbers.

-are represented as fractions and exponents (refer to Figure 6.1, page 248)

-the precision is the number of bits in the fractional part of the value that are accurate.

C/C++/C#Java

floatfloatsingle precision

doubledoubledouble precision

long double

Decimal

-decimal data types store a fixed number of decimal digits,

-with a decimal point at a fixed position in the value.

-They are stored in memory in Binary-coded decimal (BCD).

-They are available in COBOL, PL1, and C#.

Boolean types

-only two elements in the range of values (true and false).

-Usually represented using a byte.

C++/C#Java

boolboolean

Character Typescharacters are stored in computers in numeric forms:

-ASCII code (128 characters) in most programming languages

-Unicode (16-bit code) in Java, JavaScript, and C#.

Character String Type

Values consist of a sequence of characters

Is a primitive data type in FORTRAN 95 and BASIC with the following operations: assignment, relational operator, catenation, and the substring reference operations.

Is not a primitive data type in C, C++, C#, or Java

  • C
  • use char arrays to store Null terminated character strings
  • use of standard library functions (strcpy( ), strcat( ), strlen( ), strcmp( ), etc.) to provide operations on strings.
  • C++
  • Use of char arrays as in C.
  • Use of the string class from the standard library.
  • Java
  • Use the String class for constant strings
  • Use the StringBuffer class for variables whose values are changeable.

String Length

  • Static length strings: The length of the string is set when the string is created. This is the case for the Java String class, the C++ string class, and the .NET class library available in C#.
  • Limited dynamic length strings: string have a varying length up to a declared fixed maximum set by the variable definition. This is the case in C/C++. But in C/C++, the end of a string is marked by the null character: a run-time descriptor is not needed.
  • Dynamic length strings: variables have varying length with no maximum. This is the case in JavaScript and Perl.

Implementation of character string types - compile/run time descriptors (refer to page 254)

Binding

Binding is an association, such as between an attribute and an entity, or between an operation and a symbol.

Examples:

The association of a variable to a memory location.

The association of the symbol + to addition.

Binding timethe time at which a binding takes place.

Binding Times

  1. Language design time: Example, the symbol + is bound to addition of integers/ real numbers.
  2. Language implementation/compiler design time: Example, the range of possible values is associated to a data type.
  3. Compile time: Example, a variable is bound to a data type.
  4. Linkage time: Example, a call to a library function is bound to that function code, or a reference to an external global variable is bound to that variable.
  5. Load time: Example, a global variable is bound to a memory location.
  6. Execution time: Example, the binding of a local variable to a memory location.

A Binding is staticif it occurs before runtime and remains unchanged throughout the program execution.

Example:binding of a data type to a variable.

A binding is dynamicif it occurs during the execution of the program or can change during the execution of the program.

Example: binding of local variables to memory locations.

Type Bindings

How is the type of a variable specified?

When does binding take place?

Static type binding:

A type is bound to a variable by using a declaration statement:

Explicit declaration:

Examples(in C/C++ language):int num1, num2;

Implicit declaration:

Examplesin FORTRAN, an identifier that is not explicitly declared is an integer if it starts with I, J, K, L, M, or N; otherwise it is a real.

Other languages with implicit declarations are PL/1, BASIC, Perl, . . . , etc

Note:distinguish between declaration of a variable and definition of a variable in C/C++:

Example (Definition of variable in C++):int num;//a memory location will be created of variable num

Example (Declaration of variable in C++):extern int num;// a memory location is not created

Dynamic Type Binding (APL and SNOBOL)

A variable is bound to a type when it is assigned a value (in an assignment statement).

This provide programming flexibility

Example:in APL, or SNOBOL, a variable LIST could be bound to a list of integer values, a list of floating-point values, and an integer value in the same program

LIST < -----10.2 7.5 - 10.4 23.5

LIST< ----12 25 46

LIST< ----45

Type Inference (ML, Miranda, and Haskell)

Types are determined from the context of the reference of the variable.

Example:Declaration of a function in ML:

fun circleArea( r ) = 3.1415 * r * r ;

specifies a function that takes a real argument and returns a real result.

fun times10( r ) = 10 * r ;

specifies a function that takes an integer argument and returns an integer result.

fun square( r ) : int = r * r ;// the type is explicitly specified

fun square( r ) = r * (r : int);// the type is explicitly specified

Named Constants

A named constant is a variable that is bound to a value only when it is bound to a memory location.

Advantages:make the program more readable and easy to modify.

The initialization expression is specified as follows:

  • A constant is Pascal.
  • A constant-valued expression in Modula-2 and FORTRAN
  • Any kind of expression if Ada, C++, and Java

Examples:

In C++,const int val = 2 * width + 5;

In Java,final int len = 100;

Variable Initialization

The binding of a variable to a value at the time it is bound to a memory location is called initialization.

Initialization is often done in the declaration statement.

Examples:

In Ada,SUM : FLOAT := 0.0;

In C++,int num = 50;

Expressions and Assignment Statements

Expressions are the fundamental means of specifying computations in a programming language.

Arithmetic Expressions

Primary issues to consider:

  1. What are the arithmetic operators of the language?
  2. What are the operator precedence rules?
  3. What are the operator associativity rules?
  4. What is the order of operand evaluation?
  5. Are there restrictions on operand evaluation side effects?
  6. Does the language allow user-defined operator overloading?
  7. What mode mixing is allowed in expressions?

Binary Arithmetic Operators in C/C++

Operation / Operator / Example / Operand / Result
Addition / + / A + B / Both integers
------
One operand is not integer / Integer
------
Double precision floating-point
Subtraction / - / A – B / Both integers
------
One operand is not integer / Integer
------
Double precision floating-point
Multiplication / * / A * B / Both integers
------
One operand is not integer / Integer
------
Double precision floating-point
Division / / / A / B / Both integers
------
One operand is not integer / Integer
------
Double precision floating-point
Modulus (Remainder) / % / A % B / Both integers / Integer

Evaluating Simple Arithmetic Expressions

Arithmetic expressionResult

12 + 921

18 - 135

14.78 + 3.5118.29

12.50 * 450.00

15 / 27

15 % 21

15. / 27.50

8 / 3.02.666....

Unary Arithmetic Operators in C/C++ and Java

Unary Plus ( +A ):Examples:+num, +num / 5,num1 * +num2

It has no effect on its operand in C/C++.

In Java, it causes an implicit conversion of a char, short, or byte operand to int type; otherwise, it has no effect on its operand.

Unary Minus ( - A ):Examples:-num, -num / 5,num1 * -num2

The pre-increment Operator:is specified as follows:++<variable-name>

It says to add 1 to the current value of the variable and then to use the new value (if necessary).

The post-increment Operator:is specified as follows:<variable-name>++

It says to use the current value of the variable (if necessary) and then add 1 to it.

The pre-decrement Operator:is specified as follows:- - <variable-name>

It says to subtract 1 from the current value of the variable and then to use the new value (if necessary).

The post-decrement Operator:is specified as follows:<variable-name> - -

It says to use the current value of the variable (if necessary) and then subtract 1 from it.

Examples

a) int num = 5;

num++ ; // the value of variable num is not used//num = 6

b) int num = 5;

++num; // the value of variable num is not used//num = 6

c) int num1 = 5, num2 = 5, result1, result2;

reult1 = ++num1 - 3; // add 1 to the value of num1, then use it //num1 = 6 and result1 = 3

result2 = num2++ - 3; // use the value of num2, then add 1 to it//num2 = 6 and result2 = 2

d) int num = 5;

num - - ; // the value of variable num is not used//num = 4

e) int num = 5;

- - num; // the value of variable num is not used//num = 4

f) int num1 = 5, num2 = 5, result1, result2;

reult1 = - - num1 + 3; //subtract 1 from the value of num1, then use it //num1 = 4 result1 = 7

result2 = num2 - - + 3; // use the value of num2, then subtract 1 from it//num2 = 4 result2 = 8

Operator Evaluation Order

Precedence:in C++ and Java

Highest++, - - (postfix and prefix)

Unary +, -

*, / , %

LowestBinary + , -

Associativity:in C++ and Java

Left-to right:* , / , % , binary +, binary –

Right-to left:++ , - - , unary - , unary +

Examples

num1 + num2 – num3 + num4---->( ( ( num1 + num2 ) – num3 ) + num4 )

- num1++ * num2 + - - num3 ---->( ( ( - (num1++) ) * num2 ) + ( - - num3 ) )

- num1 % num2 * num3 - num4 / 6---->( ( ( ( - num1) % num2 ) * num3 ) – (num4 /6 ) )

Parentheses

The precedence and the associativity rules can be altered by placing parentheses in expressions.

A parenthesized part of an expression has precedence over its adjacent un-parenthesized parts.

User-Defined Operator Overloading

User-defined operator overloading is allowed in C++, but not in Java.

Operand Evaluation Order

Operand evaluation order refers to the order in which the values of the operands of an expression are fetched from the memory.

For example, in the expressionA + B

Is the value variable A obtained before that of variable B or that of variable B is obtained before?

This order is important if one of the operands of an expression has side effects.

A functional side effect occurs when in a function call, the values of one or more arguments or global variables are changed.

The order of operand evaluation is left-to-right in Java; it is not specified in C++.

Avoid expressions with side effects in any language.

Examples

int global = 5;

int funct1 ( int val )

{

val ++;

global ++;

return val;

}

int funct2 ( int val, int & para)

{

val++;

para ++;

return val;

}

int main ( )

{

int num1 = 5, result1, result2;

result1 = global + funct1(10 );

result2 = num1 + funct2 ( 10, num1 );

cout < “global=\t” < global < “\t result1=\t” < result1;

cout < “num1=\t” < num1 < “\t result2=\t” < result2;

return 0;

}

Operands are evaluated Left-to Right:

result1 = global + funct1( 10 );

result1 = 5 +val = 10;

val++;

global++;

return val;

result1 = 5 + 11;global = 6

result2 = num1 + funct2(10, num1 );

result2 = 5 +val = 10;

val++;

num1++;

return val;

result2 = 5 + 11;num1 = 6

The output is:

global = 6result1= 16

num1 = 6result2= 16

Operands are evaluated Right-to Left:

result1 = global + funct1( 10 );

result1 = global +val = 10;

val++;

global++;

return val;

result1 = 6 + 11;global = 6

result2 = num1 + funct2(10, num1 );

result2 = num1 +val = 10;

val++;

num1++;

return val;

result2 = 6 + 11;num1 = 6

The output is:

global = 6result1= 17

num1 = 6result2= 17

Type Conversions

A mixed-mode expression is an expression in which one or more operators have operands with different data types.

Example

int num = 3;

double result, dnum = 12.5;

result = dnum / num;

A language that allows mixed-mode expressions must provide a rule for implicit operand type conversions (or coercion) because computers do not have binary operations that take operands with different data types.

A narrowing conversion converts a value to a type that cannot store even approximations of all of the values of the original type. For example, a double to int in C++.

A widening conversion converts a value to a type that can include at least approximations of all the values of the original type. For example, an int to float in C++ and Java.

An assignment conversion is an implicit conversion that occurs when the l-value (variable) and the value of the expression (r-value) in the assignment statement do not have the same data type.

Examples

char var;

int num1, num2;

double dnum1, dnum2;

cin > num1 > dnum1;

var = num1 /2;// the integer result is converted to a character value

dnum2 = dnum1 / num1;// the integer value in the variable num1 is converted to

// a double precision floating-point value

Explicit type conversions are specified by programmers by using operations provided by the language.

In C-based languages, these operations are called casts:

Examples:

var = (char) (num1 /2);// the integer result is converted to a character value

dnum2 = dnum1 / (double) num1;// the integer value in the variable num1 is converted to

// a double precision floating-point value

Logical Expressions

A logical expression (or condition) is an expression that evaluates to either true or false.

There are two types of conditions: simple conditions and Compound conditions.

A simple condition has the following syntax:

<arithmetic expression> <relational operator> <arithmetic expression>

Relational Operators

C/C++ Symbol / Meaning
is less than
is greater than
= = / is equal to
<= / is less than or equal to
>= / is greater than or equal to
!= / is not equal to

A compound condition is built from simple conditions and logical operators.

Logical Operators

C++ Symbol / Meaning / Evaluation
AND / <condition1> & <condition2> is true if and only if both conditions are true
|| / OR / <condition1> || <condition2> is true if and only if at least one of the two conditions is true
! / NOT / !<condition> is true if and only if <condition> is false

Evaluations of compound conditions

Assuming that the variables are defined and initialized as follows:

int num1 = 5, num2 = 7, num3 = 2;

float fnum = 11.75;

char ch = ‘K’;

Compute the true value of each of the following compound conditions:

a)num1 >= 5 || num2 + 3 == num3d)num2 + 3 == num3 * 4 || ch >= ‘Z’

b)‘A’ <= ch& fnum + 7.2 != 2.5e)num1 < 3 & num2 > num3

c) !(3 * num1 + 4 < num3 * 2)f)num1 + 4 > num3 || fnum > num1 + 20 & num3 < 5

Solutions

a) num1 >= 5 || num2 + 3 == num3d)num2 + 3 == num3 * 4 || ch >= ‘Z’

5 >= 5 || 7 + 3 == 2 * 4 || ‘K’ >= ‘Z’

True 10 == 8 || False

TrueFalse||False

False False

b) ‘A’ <= ch& fnum + 7.2 != 2.5e)num1 < 3 & num2 > num3

‘A’ <= ‘K’& 11.75 + 7.2 != 2.5 5 < 3 &

True& 18.95 != 2.5 False

TrueTrue False

True

c) !(3 * num1 + 4 < num3 * 2)f)num1 > num3 || fnum > num1 + 20 & num3 < 5

!( 3 * 5 + 4 < 2 * 2) 11.75 > 5 + 20

!( 19 < 4) 11.75 > 25

! False false

True5 > 2||false

True|| false

True

There is a short-circuit evaluation of a compound condition when its true value is determined without evaluating all its individual conditions as in a), e), and f) above. Also notice in f) than the & operator has higher precedence than the || operator.

In C++, 0 is false and anything else is true. But this is not the case in Java. So, the C++ conditions !num (which is equivalent to num = = 0) is not valid in Java.

Precedence of C/C++ Operators

Operator / Order of Evaluation / Precedence
!
Unary – / right to left / 7
*
/
% / left to right / 6
+
- / left to right / 5
<=
<= / left to right / 4
==
!= / left to right / 3
left to right / 2
|| / left to right / 1

Accuracy of Floating-Point Values

The fact that floating-point values are approximated inside a computer makes it difficult to test for the equality of floating-point values.

For example, if the variable fnum is defined as follows:floatfnum = 7.1;

Then, the condition:fnum / 2 == 3.55 may not be true.

The problem may be solved by assuming that two floating-point values are equal if their difference is relatively very small.

This is done by testing if the absolute value of their difference is less than a certain value chosen by the programmer (for example 0.000001).

Using the library function fabs() that takes as argument a floating-point value and returns its absolute value, the condition:

value1 == value2

is replaced with the condition:fabs(value1 - value2) < 0.000001

which tests whether the difference between the two values is small enough so that we can make them equal.

Assignment Statements

An assignment statement is used to store a value into a memory location.

Simple Assignments

Example

InC/C++and Java,the syntax of the assignment statement is:<variable> = <expression>;

for example:

int num1, num2 = 15;

num1 = num2 * 7;

Assignment as an Operator in C/C++ and Java

In C-based languages (C/C++ and Java), the assignment is an operator that produces a result which is the same as the value assigned.

It has the right-to-left associativity.

Examples in C/C++

int num1, num2, num3, ch;