Instructions in C/C++
Instructions in C/C++
2
1. Introduction
Instructions (statements) represents the basic elements
of a program, describing what a program will process
Each instruction will have a side-effect:
The program statement will be modified (a variable will be
modified after an assignment)
The effect of instructions will be combined to obtain a result
3
At run-time a program will mostly be involved to execute
instructions
The instructions will define a flow control managed by
the CPU
C language is a structural language that will consider the
following instructions:
sequential (compound)
conditional
anterior loop
To facilitate the programming process a posterior loop, selective
instruction, and other instructions were introduced
4
Types of instructions:
label
expression
compound
conditional
loops
jump
declarations
5
2. Expression Instruction
Syntax:
[expression];
Particular case:
Simple assignment: i=5;
Function call: getch( );
empty: ;
No effect code: i+j;
6
3. Compound Instructions
Declarations and instructions between curly braces { }
Syntax:
{
[local declarations]
instructions set
}
The aim:
To consider a set of instructions instead of one
Allows to specify a block zone - domain
7
In C language a block is declared before the instructions
at the beginning
In C++ no restrictions
The validity domain of variables is limited to the block and
the time duration depends on execution time for the block
8
After final brace no semicolon, ;!
Inside a block may appear other blocks:
{
[local declarations]
instructions set
{
[local declarations]
instructions set
}
}
9
4. Conditional Instruction
if...else instruction
Allows a decision with one condition
Syntax:
if(expression) or if(expression)
instr1 instr1
else
instr2
where expression is a scalar value
if and else are key words
If expression is different zero (true) instr1 is executed,
otherwise instr2
Finally the first instruction after if-else will be executed
exception: break, continue or goto will change that
10
Because the condition is numeric is allowed to use:
if(expression) instead of if(expression != 0)
The ifelse syntax considers only one instruction on
an if or else branch:
A compound instruction may be used for complex activities
Imbricated if...else instruction:
if(expression1)
if(expression2)
instr1
else
instr2
else
if(expression3)
...
11
Because else is optional, it is possible to have an
ambiguity concerning when an else is omitted from an
imbricated if sequence:
else will be implicit associated to the appropriate if from the
same block that has no associated else
if(expression1)
if(expression2)
instr1
else
instr2
else belongs to the inner if
12
If instr1 and instr2 are expression instructions we may
use the conditional operator ?:
expr ? expr1 : expr2 equivalent with if(expr)
expr1
else
expr2
13
else-if constructions are allowed to express multiple
decisions:
if(expression1)
instr1
else if(expression2)
instr2
else if(expression3)
instr3
else
instr4
No restrictions concerning the number of else-if
between an initial if and a final else
14
Example: degree I equation
double a,b;
if(scanf("%lf %lf", &a, &b) != 2)
printf("coeficienti eronati\n");
else
if(a != 0)
printf("a=%g\tb=%g\tx=%g\n", a,b, -b/a);
else
if(b== 0)
printf("ecuatie nedeterminata\n");
else
printf("ecuatia nu are solutie\n");
15
switch instruction
Allows multiple selection if is controlled by the value
of an expression
Syntax:
switch(expression)
{
case const
1
:
lista_instr
1
;
[break];
case const
2
:
lista_instr
2
;
[break;]
...
[default:]
lista_instr;
//[break;]
}
16
Where:
switch, case, default, break are key words
expression is an expression with integer, character or constant
value
No float, double or struct types
const
i
are selection constants with distinct values compatible
with the type of the expression
lista_instr
i
is a sequence of instructions
Effect:
Expression is evaluated and compared with selection constants
If it is equal the associate instructions are executed
If no equality the default, part will be executed, if exists
17
break instruction will stop the execution of switch
instruction
We may associate more case labels to the same action
18
switch (operator)
{
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case 'x':
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
cout << "unknown operator: " << ch << '\n';
//break;
}
19
Any switch instruction may be replaced by an equivalent if-
else instruction:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
We prefer to use if-else when:
The involved expressions are complicated not simple equalities
The comparison values, labels, are expressions
switch- case no break
20
Exemplu:
switch (expresie) if (expresie == c1)
{ {
case c1: sir_1; sir_1;
case c2: sir_2; sir_2;
} }
= else
if(expresie == c2)
{
sir_2;
}
Multiple switch-case
21
Exemplu:
char ch;
printf(Introdu o litera);
ch=getche();
switch(ch)
{
case a:
case e:
case i:
case o:
case u:
printf(\nEste o vocala);break;
default: printf(\nEste o consoana);
}
22
5. Loop Instructions
Why to use?:
To process data of same type (usual arrays)
Same operations in repeated mode
The syntax considers anterior ( while (), for() )
and posterior instructions (dowhile()) combined
with composed instructions
23
while( ) instruction:
Anterior loop- initial test
Syntax:
while(expression)
instruction
while is a key word
Effect:
Instruction is executed till the expression is true
24
No or infinite executions depending on the condition:
while(0);
while(1);
Usual the condition is modified by inside instructions
Instruciuni de ciclare
25
Example:
int num;
num = 0;
while (num < 10)
{
printf("num = %d", num);
num++;
}
...
int contor;
contor = 1000;
while(contor--);
Reverse elements of an array
26
Exemplu:
float tab[10],tmp;
int l=0,j=9;
// inverseaza elementele din tab
while(l<j)
{
tmp=tab[l];
tab[l]=tab[j];
tab[j]=tmp;
l++;
j--;
}
27
for() instruction:
Anterior loop with a fix number of steps
for is a key word
Syntax:
for([expression1]; [expression2]; [expression3])
[instr]
Similar effect with the following while() :
[expression1;]
while([expression2])
{
[instr]
[expression3];
}
28
expression1, is evaluated once before the first
iteration
Used for init: cycle counter and/or other parameters
expression2, is evaluated and tested before each
iteration
It is the condition to leave the loop
expression3, is evaluated at the end of each iteration
Used to update the cycle parameters
29
Any expression may miss
Delimitators ";" are compulsory : for(;;)
Example:
#define N 100
...
int i, tab[N];
...
for(i=0;i<N;i++)
printf("\n\t %d", tab[i]);
#define N 10
...
int n, fact;
...
for(n=N, fact = 1; n; n--) fact *= n;
for <-> while
30
for(exp1;exp2;exp3) exp1;
{ while(exp2)
instructiuni; {
} instructiuni;
exp3;
}
sau
while (expresie) for(;expresie;)
{ {
instructiuni; instructiuni;
} }
31
Imbricated loop instructions
As instruction in a loop may be any instruction,
including other loop instruction, in this case we
consider, imbricated loop instructions
Imbricated loop instructions are used usual to process
multi-arrays
Example: generate pair values
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
cout << '(' << i << ',' << j << ")\n";
32
do-while() instruction:
Allows posterior loop instructions - final test
Syntax:
do
instr
while(expression);
do and while are key words
Instruction is executed at least once till the expression
is true
33
Example:
#define ESC \x1b
int key;
...
do
{
...
if(kbhit())
key = getch();
} while(key != ESC);
34
Exemplu:
int num=0, total=0;
do //tipareste numerele naturale de la 0 la 9 si numarul lor progresiv
{
total+=num;
printf(num= %d total = %d,num,total);
num++;
}
while(num < 10)
A do while() is equivalent with a while():
instr;
while(expression)
{
instr;
}
35
36
6. Unconditional instructions
Allows to stop a sequence of code and to
continue the program from other point
break instruction:
It is used:
In a switch to mark the instructions sequence of a case
selector and to leave the switch
In loops, to force the exit condition independently
37
In imbricated instructions, break will stop the current loop
and will not affect the outside loop
Example:
#define N 25
...
int I, j;
double tab[N];
...
for(j=0;j<N;j++){
for(i=0;i<N;i++)
{
if(tab[i] < 0)
break;
else
printf("%lf", sqrt(tab[i]));
}//inside loop
//exit point from inside
.. }//outside loop
38
continue instruction:
Used in loop instructions to interrupt the current
iteration and after that:
for while and do-while the condition will be verified
for for is continued with the evaluation of expression3 and than
expression2
For imbricated loops the extern cycles will not be
affected
Example:
#define N 25
...
int i;
double tab[N];
...
for(i=0;i<N;i++)
{
if(tab[i] < 0)
continue;
printf("%d %lf", i, sqrt(tab[i]));
}
39
goto instruction:
Label instruction:
label: instruction;
Syntax: goto label;
label must be in the same function, and if more,
distinct labels must be considered
if(coderr > 0) goto iesire;
.
iesire: return (coderr);
40
41
The instruction is not compulsory:
If it is possible must not to be used
Where is used: to force the exit from imbricated loops
If it is used to abandon the current cycle exit() function
or return instruction is used
exit() function is declared in stdlib.h:
void exit(int cod);
Where for: cod = 0 , normal exit
cod != 0 , error exit, OS will analyze
42
return instruction:
Used to go back from a function
The control will be transferred to the calling function
return may appear anywhere in the function block
Types:
return;
return (expression);
The expression value (with implicit conversions) will
be transferred to the calling function:
43
A function that will return a result must contain an
instruction return (expression):
Otherwise an error or warning will be thrown
The result may be neglected
double factorial (int n)
{
double f;
int l;
if (n < 0 || n >170) return -1.0;
for(l=2,f=1.0; l <= n; l++) f* = l;
return f;
}
44