37
Structure Variables Comments Floats Simple Expressions 2. Variables, Identifiers, and Expressions 24. Juni 2011 2. Variables, Identifiers, and Expressions Einf ¨ uhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 1 of 35

2. Variables, Identifiers, and Expressions

  • Upload
    others

  • View
    25

  • Download
    0

Embed Size (px)

Citation preview

Structure Variables Comments Floats Simple Expressions

2. Variables, Identifiers, and Expressions

24. Juni 2011

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 1 of 35

Structure Variables Comments Floats Simple Expressions

Outline

• A Movie

• Structure of Simple C Codes

• Variables & Identifiers

• Comments & Documentation

• Built-in Datatypes

• Excursus: Floating Point Precision

• Simple Expressions: Assignments andBasic Arithmetics

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 2 of 35

Structure Variables Comments Floats Simple Expressions

The Golden Age of (Super)Computing

• Chris Johnson,

• head of the Scientific Computing &Imaging Institute in Salt Lake City, and

• member of the PITAC committee.

• At TUM, there’s similar institutes(organised as consortia) such as theMunich Centre of AdvancedComputing.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 3 of 35

Structure Variables Comments Floats Simple Expressions

—2.1. Structure—

# inc lude <iostream>i n t main ( ) {

std : : cout << ” He l lo yourname ” ;r e t u r n 0 ;

}

• The computer runs through the code step-by-step(left to right, top-down)

• In each step, it executes the commands(a code is a cooking instruction)

• A step is terminated by a semicolon

• main identifies the jump-in point

• std::cout plots something on the console

• return 0 makes the program terminate(return to the command line prompt)

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 4 of 35

Structure Variables Comments Floats Simple Expressions

An Addendum: C vs. C++

• C is (basically) subset of C++

• Some features were deprecated or augmented (see comments)

• Some functions were replaced, in particular the output functions

i n t a=10; double b=20;s td : : cout << ” a i s ” << a << ” and b i s ” << b ; / / C++ s t y l e

p r i n t f ( ” a i s %i and b i s %f ” , a , b ) ; / / C s t y l e

Other functions: malloc (became new), free (became delete), and structs (need aname before the bracket opens). Furthermore, some shortcuts were removed (mainalways needs a return type). The C++ typically are safer (type checks) and morepowerful.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 5 of 35

Structure Variables Comments Floats Simple Expressions

—2.2. Variables—

Let’s create a variable.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 6 of 35

Structure Variables Comments Floats Simple Expressions

Declaring a Variable

Memory

21:22;23;24; 10 x is alias25; 26;27;28:

int x;

x = 10;

• Computer runs through code step-by-step

• Declaration = define a name/alias for a memory location

• Definition = find a well-suited (free) place in memory

• Variable then is alias for this storage point⇒ we work with names instead of addresses

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 7 of 35

Structure Variables Comments Floats Simple Expressions

Identifiers

W. Savitch: A C++ identifier must start with either a letter orthe underscore symbol, and the remaining characters must allbe letters, digits, or underscore symbols. C++ identifiers are casesensitive and have no limit to their length. (p. 7)

• An identifier is (unique) name of a variable

• Must not equal a keyword

• Should have a name with a precise meaning(UNIX-style and Hungarian notation today are considered to be a bad smell)

• Examples:

• userNumber, UserNumber, userNumber, usernumber, user number• usno, usrn, usrn, nusr, usr1, usr1no• iUserNumber, intUserNumber

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 8 of 35

Structure Variables Comments Floats Simple Expressions

Built-in Datatypes

Memory

21: y // one byte22; z // four bytes23;24; 25; 26; x // two bytes?27;28:

int x;char y;float z;

• A variable corresponds to memory location and holds a value.

• What type of value?char, int, float, and double, and so forth.

• Compiler cares for memory layout.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 9 of 35

Structure Variables Comments Floats Simple Expressions

What Value Does a Variable Have By Default?

It is time for an experiment . . .

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 10 of 35

Structure Variables Comments Floats Simple Expressions

Scope of Built-in Datatypes

E. W. Dijkstra: Once a person has understood the way variablesare used in programming, he has understood the quintessenceof programming. (Notes on Structured Programming)

name size range memory footprintbool {>,⊥} 1 Byte (?)char 0 . . . 255 1 Byteshort int −32, 768 . . . 32, 767 2 Bytesint −2, 147, 483, 648 . . . 2, 147, 483, 647 4 Bytes (?)long int −2, 147, 483, 648 . . . 2, 147, 483, 647 4 Bytes (?)float ≈ ±10−37 . . .± 1038 4 Bytesdouble ≈ ±10−307 . . .± 10308 8 Bytes

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 11 of 35

Structure Variables Comments Floats Simple Expressions

Long and Unsigned Modifier

• Long Integers

long i n t a ; / / s i ze ?i n t b ; / / s i ze ?

• C/C++ standard defines at least n bits.• On 64 bit architectures, int and long int typically are the same.• Some 32 bit architectures support 64 bit integers due to a tailored compiler.• Others don’t (such as the RZG’s BlueGene/P system with the IBM compiler).• Recommendation: Avoid modifiers such as long and short.

• Unsigned Integers

unsigned i n t a ; / / s i ze ?i n t b ; / / s i ze ?

• That sign consumes one bit of the representation.• If you are sure you don’t need the sign, you can squeeze out an additional bit,• however, be careful with this!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 12 of 35

Structure Variables Comments Floats Simple Expressions

What is an Overflow?

• An excursus into binary number systems:

00000000b = 010

00000001b = 110

00000010b = 210

00000011b = 310

• ALU internal (for an inc):

• 00110111b + 00000001b• 00110111b• 00110110b• 00110100b• 00111000b

• Your turn: Increment 11111111b (it is an unsigned integer)!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 13 of 35

Structure Variables Comments Floats Simple Expressions

What is an Overflow?

• C++ does not check for overflows(unlike all the interpreted languagessuch as Java and C# that are slower inturn).

• C++ does not check for underflows(unlike all the interpreted languagessuch as Java and C# that are slower inturn).

• Now, how would you define/encodeyour signed integer in terms of bitsand what do the operations look like?

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 14 of 35

Structure Variables Comments Floats Simple Expressions

Codes for Signed Integers

• 1-2:• 00000001b - 00000001b - 00000001b• 00000001b - 00000001b• 00000000b - 00000001b• 11111111b

• -1+1:• 11111111b + 00000001b - 00000001b• 11111111b• 11111110b• 10000000b• 00000000b

• Still, the first bit is the sign, but an “overflow” is just running through zero.• There’s more negative values than positive ones.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 15 of 35

Structure Variables Comments Floats Simple Expressions

Syntax vs. Semantics

• Syntax = rules for the constructing of sentences in the languages

• Semantics = meaning of sentences, words, or fragments.

• The syntax is (more or less) prescribed by C, but

• the semantics is what you had in mind, i.e. the reader has to reconstruct it fromyour program.

• So, use meaningful names, and,

• if that is not sufficient, add documentation, documentation, and documentation.

• If code is not documented, it does not exist!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 16 of 35

Structure Variables Comments Floats Simple Expressions

—2.3. Comments—

# inc lude <iostream>/∗∗∗ This i s the famous main opera t ion .∗ Here the a p p l i c a t i o n s t a r t s .∗ /

i n t main ( ) { / / hey dude , here we go/∗∗ w r i t e yourname to the console ∗ /s td : : cout << ” He l lo yourname ” ;/ / Return to the consoler e t u r n 0 ;/∗ The comments are not

exectuded by the machine∗ /}

• C/C++ is an instruction for a computer not for a human

• Often, we (or others) do not understand from a code what is happening

• Insert comments which annotate the code

• They are thrown away by the compiler

• Syntax alternatives: C/C++/C++ (JavaDoc)

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 17 of 35

Structure Variables Comments Floats Simple Expressions

Facts About Comments

• Sad But True

• C code is difficult to understand—it ain’t literate programming (Knuth’s TEXexperience)

• Documentation (design drafts, Ph.D. theses, papers, webpages) never isup-to-date (quick-fix disease)

• After a few days, the author is not familiar with the code anymore• Every developer has a different style of writing and a different style of thinking• “I’ll comment when it is running”—that is a lie!

⇒ document everything in the code, otherwise its lost or won’t be read!

• Tools

• Best Practices

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 18 of 35

Structure Variables Comments Floats Simple Expressions

Documentation Tools

Screenshot from Doxygen

• Sad But True⇒ document everything in the code,otherwise its lost or won’t be read!

• Tools

• Idea: Extract documentation fromsource code

• Format: Webpages, PDF, TEX• Content: Diagrams,

documentation text, mathematicalformulas, images

• Tools: JavaDoc, Doxygen (bothfor C/C++)

• Best Practices

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 19 of 35

Structure Variables Comments Floats Simple Expressions

Documentation Best Practices

• Sad But True⇒ document everything in the code, otherwise its lost or won’t be read!

• Tools

• Best Practices

• Document everything in the code (first place) before you write or alter thecode.

• If you have to work with a third-party code, document it in the first place andsend it back to the authors. They’ll love you!

• Add a description before each complicated part (operations, methods, . . . ).• Make yourself familiar with the tools and add formulas and images to your

documentation.• Document what, why, rationale, alternatives, and bugs fixed.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 20 of 35

Structure Variables Comments Floats Simple Expressions

Screenshot

isPassivePeano - Source Directory and Architecture grid AbstractVertex<> isPassive

SearchHelp

grid

Directoriesadaptercheckpointconfigurationintegration-testsmulticorerecordsrunnersstatisticstests

ClassesAbstractCell<>AbstractLeafEvent<>AbstractNewEvent<>AbstractPersistentRefined.AbstractRefinedEvent<>AbstractRootEventAbstractStackBasedRefined.AbstractVertex<>Block<>BlockContainer<>Event<>EventHelperGridCellGridVertexLeafEvent<>NewEvent<>PassiveLeafEvent<>PassiveNewEvent<>PassivePersistentRefinedE.PassiveRefinedEvent<>PersistentRefinedEvent<>RefinedEvent<>RootEvent<>StaticLeafEvent<>

Description Source Call Graph

peano::grid::AbstractVertex::isPassive ( Const Public Method )Author: Tobias Weinzierl

Is Vertex Passive.

Syntax / parameters

Return value

DescriptionIs Vertex Passive.If a vertex is passive, the event handler is not called for this vertex. A vertex is set passive by the NewEvent::createVertex() operation if the vertex and thewhole surrounding support are outside of the domain.

Be careful to make any vertex outside the computational domain a passive vertex. If you want to plot boundary cells, e.g., you have to ensure that all thevertices are plotted before you plot your cells. Yet, the touch operations are not invoked for passive vertices.

In the parallel mode, each vertex is set passive that does not hold the actual node as adjacent element. Thus, vertices outside the computational partition areset passive although they might be inside the computational domain. This switch is implemented within derivePersistentVertexDataFromCoarseGrid().

Peano-Sources - isPassive http://www5.in.tum.de/peano/src/src/grid/isPassive3949054044_member_description.html

1 von 3 07.06.2010 16:07

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 21 of 35

Structure Variables Comments Floats Simple Expressions

—2.4. Floats—

# inc lude <iostream>

i n t main ( ) { / / hey dude , here we godouble a ;double b ;double c ;a = 0.145e−07;b = 23.24e09 ;c = a+b ;s td : : cout << c ;

}

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 22 of 35

Structure Variables Comments Floats Simple Expressions

A Gedankenexperiment—Fixed-point notation

• A number in a computer has to have afinite number of bits.

• This means a finite number of digits.

• Let’s assume we have four digits in theform xx .yy .

a = 01.50;b = 00.50;c = a / b ;d = c / 3 ;

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 23 of 35

Structure Variables Comments Floats Simple Expressions

Floating-point notation

• A dynamic scheme (with a header, e.g.) cannot be fast (although Maplee.g. supports this if we need arbitary number of significant/valid digits).

• Define number into significant digits and exponent.• Make the representation unique, i.e. ab.cd · 104 = a.bcd · 105. This is a

normalisation.• In a binary system, base is 2 and first digit before comma always is 0 (or 1

respectively).• So, we need one bit for the sign, s bits for the significant digits, one bit for the sign

of the exponent, and e bits for the exponent.

Type Sign Exponent Significand Total bitsSingle 1 8 23 32Double 1 11 52 64

This is a ’at least’ standard! And there’s two additional/special values: nan and inf.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 24 of 35

Structure Variables Comments Floats Simple Expressions

Normalisation & round-off errors

# inc lude <iostream>

i n t main ( ) {/ / hey dude , here we go

double a ;double b ;double c ;a = 0.145e−07;b = 23.24e09 ;c = a+b ;s td : : cout << c ;

}

Use your pocket calculator and assume the-re’s eight significant bits!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 25 of 35

Structure Variables Comments Floats Simple Expressions

Normalisation & round-off errors

C1 =N∑

i=1

i

C2 =

N/2∑i=1

(i + N − i)

• Which variant is the better one?• What means stability in this context?• Why is the condition number important

within this context?

We have to study all our algorithms in de-tail!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 26 of 35

Structure Variables Comments Floats Simple Expressions

Some remarks on performance

• A Flop is a floating point operation.• A MFlop is a . . . ?• How many Flops does the SuperMUC provide?• If one of these GPGPU guys tells you something about performance, ask him

about which precision he is using!

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 27 of 35

Structure Variables Comments Floats Simple Expressions

—2.5. Simple Expressions—

The Assignment Statement

Memory

21:22;23;24; 10 x is alias25; 26;27;28:

int x;

x = 10;

The assignment operator takes expressionfrom the right-hand side, evaluates it, andstores the result in the variable on the left-hand side.From a mathematical point of view, choo-sing = as assignment operator is a poorchoice. Pascal, e.g., uses the := operator,which, from the author’s point of view, is abetter symbol.A declaration can directly be combined withan assignemnt.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 28 of 35

Structure Variables Comments Floats Simple Expressions

Arithmetic Expressions (for Numbers)

• c=10+2; — assign variable c the value 12.

• a=10; b=a; a=2; — afterwards, a holds 2 and b holds 10, i.e. a 6= b.

• c=10*2; — assign variable c the value 20.

• b=3; a=(b+2)*10; — assign variable b the value 3. a becomes 50.

• a=2; a=a*2; — this ain’t a fixpoint formula, i.e. a holds the value 4 afterwards.

• a=3; a++; — increment operator makes a hold 4.(unary operator)

• a=3; a--; — decrement operator.

• a=2; a+=4; — shortcut for a=a+4.

• a=2; a-=4; — shortcut for a=a-4.

• a=2; a*=4; — shortcut for a=a*4.

• a=a/2; — divide value of a by 2.

• a=4; a/=2; — shortcut for a=a/2.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 29 of 35

Structure Variables Comments Floats Simple Expressions

Further Expressions

• For booleans

• bool a=true;

• bool a=false;

• bool a=0;

• bool a=1;

• bool a=2;

• a=!a;

• a=!(a | a);

• For characters

• char x=’a’;

• char x=40;

• Comparsions

• bool x=a>4;

• bool x=a>b;

• bool x=a==b;

• bool x=a!=b;

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 30 of 35

Structure Variables Comments Floats Simple Expressions

Fancy Initialisation

: In C++, you can initialise all variables with brackets!

int a = 10; int a(10);

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 31 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls I—Multiple Declarations

• int a;

int b;

• int a,b; — Shortcut

• int a,b =2 ; — What does thismean?

⇒ either declare one variable per line or use C++ initialisation with brackets.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 32 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls I—Multiple Declarations

• int a;

int b;

• int a,b; — Shortcut

• int a,b =2 ; — What does thismean?

⇒ either declare one variable per line or use C++ initialisation with brackets.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 32 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls II—Implicit Type Conversion

• double a;

• double a=0.3;

• double a=10.0 / 4.0;

• double a=10.0 / 4;

• double a=10 / 4;

⇒ If you use floating point arithmetics always write .0 for natural numbers.⇒ If you are interested in the underlying techniques, study the field of type inference.⇒ If you wanna have a more dynamic feeling, use a language with a dynamic typesystem.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 33 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls II—Implicit Type Conversion

• double a;

• double a=0.3;

• double a=10.0 / 4.0;

• double a=10.0 / 4;

• double a=10 / 4;

⇒ If you use floating point arithmetics always write .0 for natural numbers.⇒ If you are interested in the underlying techniques, study the field of type inference.⇒ If you wanna have a more dynamic feeling, use a language with a dynamic typesystem.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 33 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls III—Assignment Operators

int a = 3

bool b = (a==3);

bool c = (a=3);

int d = 0

bool e = (d==0);

bool f = (d=0);

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 34 of 35

Structure Variables Comments Floats Simple Expressions

Initialisation Pitfalls IV—Freaky Collaborators

int a = 3; int b = ++a; (that is want we want)int c = 3; int d = c++; (that is something different)

int e = (d+=a)++; (also very funny)int f = ((d=4)+a)--;

⇒ C/C++ offer many strange constructs. This is good luck for posers, freaks, andpeople giving lectures. Others should avoid them.

2. Variables, Identifiers, and Expressions

Einfuhrung in die Programmierung—Introduction to C/C++, Tobias Weinzierl page 35 of 35