38
Imperative programming Overview Tamás Kozsik and others ELTE Eötvös Loránd Tudományegyetem

Tamás Kozsik and others ELTE Eötvös Loránd Tudományegyetem

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Imperative programmingOverview

Tamás Kozsik and others

ELTE Eötvös Loránd Tudományegyetem

Imperative programming

Statements, control structuresReading and writing memoryC programming language (link!)

Tamás Kozsik and others (ELTE) Overview 2 / 31

Imperative programming

Statements, control structuresReading and writing memoryC programming language (link!)

Tamás Kozsik and others (ELTE) Overview 2 / 31

Imperative programming

Statements, control structuresReading and writing memoryC programming language (link!)

Tamás Kozsik and others (ELTE) Overview 2 / 31

Imperative programming

Statements, control structuresReading and writing memoryC programming language (link!)

Tamás Kozsik and others (ELTE) Overview 2 / 31

Outline

1 Structure of programsCompilation and running of programs

Structure of programs

Structure of programs

Keywords, literals, operators, other signs, identifiersExpressionsStatementsSub-programs (functions/procesures, routines, methods)Modules (libraries, classes, packages)

Tamás Kozsik and others (ELTE) Overview 4 / 31

Structure of programs

Example

int factorial( int n )

{

int result = 1;

int i;

for(i=2; i<=n; ++i)

{

result *= i;

}

return result;

}

Tamás Kozsik and others (ELTE) Overview 5 / 31

Structure of programs

Example

int factorial( int n )

{

int result = 1;

int i;

for(i=2; i<=n; ++i)

{

result *= i;

}

return result;

}

Tamás Kozsik and others (ELTE) Overview 5 / 31

Structure of programs

Expressions

n

"Hello world!"

100

n+1

++i

range(2,n+1)

employees[factorial(3)].salary * 100

Tamás Kozsik and others (ELTE) Overview 6 / 31

Structure of programs

Statements

result = 1;

result *= i;

return result;

for( i=2; i<=n; ++i ){ result *= i; }

while(1) printf("Gyurrrika szép!\n");

Tamás Kozsik and others (ELTE) Overview 7 / 31

Structure of programs

Simple statements

assignment (expression evaluation statement)null statementsub-program callreturning from a function

Tamás Kozsik and others (ELTE) Overview 8 / 31

Structure of programs

Control structures

branchesloops etc.

int gcd( int n, int m )

{

while( n != m )

if( n > m )

n -= m;

else

m -= n;

return n;

}

Tamás Kozsik and others (ELTE) Overview 9 / 31

Structure of programs

Curly braces in control structures

Omitted curly bracesint gcd( int n, int m )

{

while( n != m )

if( n > m )

n -= m;

else

m -= n;

return n;

}

Foolproof solutionint gcd( int n, int m )

{

while( n != m ){

if( n > m ){

n -= m;

} else {

m -= n;

}

}

return n;

}

Tamás Kozsik and others (ELTE) Overview 10 / 31

Structure of programs

Dangling else

I wrote thisif( x > 0 )

if( y != 0 )

y = 0;

else

x = 0;

Means thisif( x > 0 )

if( y != 0 )

y = 0;

else

x = 0;

I wanted thisif( x > 0 ){

if( y != 0 )

y = 0;

} else

x = 0;

See…goto-fail (Apple) link!

Tamás Kozsik and others (ELTE) Overview 11 / 31

Structure of programs

Printing to the standard output

Print an integer and a new line character

printf("%d\n",factorial(10));

Tamás Kozsik and others (ELTE) Overview 12 / 31

Structure of programs

More complex print

printf("10! = %d, ln(10) = %f\n", factorial(10), log(10));

10! = 3628800, ln(10) = 2.302585

Tamás Kozsik and others (ELTE) Overview 13 / 31

Structure of programs

More complex print

printf("10! = %d, ln(10) = %f\n", factorial(10), log(10));

10! = 3628800, ln(10) = 2.302585

Tamás Kozsik and others (ELTE) Overview 13 / 31

Structure of programs

Types

Express the way bit sequence is interpretedDetermine the possible values of a variableDetermine the possible operations on values

In Cint – an interval of integers, e.g. [−231 .. 231 − 1]float – subset of rational numberschar – characterschar[] – texts, array of charactersint[]– array of integersint* – pointer to an integer

etc.

Tamás Kozsik and others (ELTE) Overview 14 / 31

Structure of programs

Values of different type in the memory

Tamás Kozsik and others (ELTE) Overview 15 / 31

Structure of programs

Values of different type in the memory

Tamás Kozsik and others (ELTE) Overview 15 / 31

Structure of programs

Values of different type in the memory

Tamás Kozsik and others (ELTE) Overview 15 / 31

Structure of programs

Role of types

Protection against programming errorsExpress the intention of programmersHelp forming abstractionsHelp efficient code generations

Tamás Kozsik and others (ELTE) Overview 16 / 31

Structure of programs

Type checking

Checks whether variables and functions are used according to theirtypesNon type correct programs are meaningless

Static and dynamic type systemC compiler checkes type correctness in compile time

Strongly and weakly typed languagesIn a weakly typed language values are automatically converted toother types if needed

Seems comfortable for the first sightWe can easily write something else than we wanted

Rules in C are relatively strict (quite strongly typed)

Tamás Kozsik and others (ELTE) Overview 17 / 31

Structure of programs

Subprograms

Description of multi-step computationsGeneral, can be parameterized, reusableStructuring programs – handling complexity

Shouldn’t be longer than a page

Has different namesroutine or subroutinefunctions: computes a value and “returns’ ’ itprocedure: changed program statemethod: object oriented terminology

Tamás Kozsik and others (ELTE) Overview 18 / 31

Structure of programs

Main program

Where program execution starts

CA subprogram with a given name: main Egy megfelelő nevű alprogram:main

int main()

{

int half = 21;

printf("%d\n",2*half);

return 0; /* sikeres végrehajtás */

}

Tamás Kozsik and others (ELTE) Overview 19 / 31

Structure of programs

Comment

int main()

{

int half = 21;

printf("%d\n",2*half);

return 0; /* Here I write a comment */

}

Tamás Kozsik and others (ELTE) Overview 20 / 31

Structure of programs

Module

Modularity: encapsulation, independence, tight interface

Reusable librariese.g. the standard library of the language

Bigger program unitsImplementation of abstractions

Tamás Kozsik and others (ELTE) Overview 21 / 31

Structure of programs

Breakdown into modules

Reusable factorial

factorial.c – factorial functiontenfactorial.c – main program

tenfactorial.c#include <stdio.h>

int factorial( int n ); /* Declaration of this function */

int main()

{

printf("%d\n", factorial(10));

return 0;

}

Tamás Kozsik and others (ELTE) Overview 22 / 31

Structure of programs Compilation and running of programs

Source code

Code written in a programming languageComputer: machine codeExecution

interpretationcompilation, running

Source file, e.g.: factorial.c

Tamás Kozsik and others (ELTE) Overview 23 / 31

Structure of programs Compilation and running of programs

Interpreter

Processes source code by statementsReporting errors in case of erroneous statementsExecution in case of no errors

Execution of a statement: based on built-in machine code

DisadvantagesRun-time error in case of erroneous program (rarely executedstatement???)Slower execution

AdvantagesIntegration of program writing and execution

REPL = Read-Evaluate-Print-LoopFast prototyping

Beginners may learn it easierTamás Kozsik and others (ELTE) Overview 24 / 31

Structure of programs Compilation and running of programs

Source code in Cfactorial.c#include <stdio.h>

int factorial( int n ){

int result = 1;

int i;

for(i=2; i<=n; ++i){

result *= i;

}

return result;

}

int main(){

printf("%d\n", factorial(10));

return 0;

}

Tamás Kozsik and others (ELTE) Overview 25 / 31

Structure of programs Compilation and running of programs

Separation of compilation and running

A lot of programming errors can be determined without running theprogramWe can examine the program in advanceNeeds to be done only once (during compile-time)Less error during executionGoal: efficient and reliable machine code!

“Compile time” and “runtime”

Tamás Kozsik and others (ELTE) Overview 26 / 31

Structure of programs Compilation and running of programs

Compilation and running

Source filefactorial.c

Compilationgcc factorial.c

Compiled programa.out

Execution./a.out

Tamás Kozsik and others (ELTE) Overview 27 / 31

Structure of programs Compilation and running of programs

-o flag of gcc

Source filefactorial.c

Compilationgcc -o fact factorial.c

Compiled programfact

Execution./fact

Tamás Kozsik and others (ELTE) Overview 28 / 31

Structure of programs Compilation and running of programs

Compilation errors

Violating language rulesDetected by compiler

factorial.c-benint factorial( int n )

{

int result = 1;

for(i=2; i<=n; ++i)

{

result *= i;

}

return result;

}

gcc factorial.c

factorial.c: In function ‘factorial’:

factorial.c:6:9: error: i undeclared (first use in this function)

for(i=2; i<=n; ++i)

^

Tamás Kozsik and others (ELTE) Overview 29 / 31

Structure of programs Compilation and running of programs

Compiler warnings

Language rules followedCompiler detects if something issuspiciousProbably we made a mistakeGoal: compilation withoutwarnings

factorial.c-benint factorial( int n )

{

int result = 1, i;

for(i=2; i<=n; ++i)

{

result *= i;

}

}

gcc -W -Wall --pedantic factorial.c

factorial.c: In function ‘factorial’:

factorial.c:10:1: warning: control reaches end of non-void function

[-Wreturn-type]

}

^

Tamás Kozsik and others (ELTE) Overview 30 / 31

Structure of programs Compilation and running of programs

Preprocessing

C preprocessor: creates source code (from source code)

Macros#define WIDTH 80

...

char line[WIDTH];

Sharing declarations#include <stdio.h>

...

printf("Hello world!\n");

Conditional compilation#ifdef FRENCH

printf("Salut!\n");

#else

printf("Hello!\n");

#endif

Tamás Kozsik and others (ELTE) Overview 31 / 31