C Intro2

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C Intro2 as PDF for free.

More details

  • Words: 2,373
  • Pages: 35
Introduction to C Part 2: Basics C Language Tutorial System Programming 251­0053 Fall Semester 08  Mathias Payer, RZ H11 <[email protected]>

C Introduction / Basics

1/35

Outline ●

Tutorial teaches basics of C



4 Lectures





09/25: Overview



10/02: Basic programming



10/10: Advanced programming



10/17: Environment

Hands-on work handled in exercise classes –

Debugger examples



Inlining assembler instructions

C Introduction / Basics

2/35

Overview (this lecture) ●

Variables –



Declaration and handling

Conversion and Casting –

Automatic conversion, upcasts and downcasts



Assignments and Operators



Input / Output –



The Unix I/O paradigm

Control Flow –

if and switch statements and different loop types

C Introduction / Basics

3/35

Variable declaration ●





Variables must be declared before they can be used Variables are declared at the beginning of the code block –

All variable declarations first, code later



C99 allows declaration in code blocks too

Variable names must be valid identifiers –

Keywords (void, int, struct, ...) are not allowed



A-Z, a-z and _ are allowed as first character



After the first character 0-9 are allowed as well



Watch out: C is case-sensitive -> fooBar != FoObAr Type int double char

C Introduction / Basics

Identifier foo; bar; ch; 4/35

Initial value & literals ●

Variables can have an initial value (assigned at decl.) –



int foo double xx

= 4; = 3.1415;

Other literals and types: –

Literals are used in the code to specify a numeric value



int:

23



long:

2342l (l as in Lancelot)



double: 23.42 23.42d 2.3e42 (=2.3 * 1042)



float: 42.23f 4.2e-23 (=4.2 * 10-23)



char:

C Introduction / Basics

'c'

5/35

Constants ●









A constant is a variable that cannot be changed after its initialisation C has the keyword const to tell the Compiler that a value is constant –

const int MAX_CHAR = 255;



const double PI = 3.1415;

The keyword is a prefix to the variable type Only a (compile) warning message is printed if a constant is overwritten in the program Aliasing can overwrite constants –

Leads to strange effects (register vs. fetch from memory)

C Introduction / Basics

6/35

Variable scope int x; // in global scope int main() { while (...) { ... }

}

C Introduction / Basics

7/35

Variable scope int x; int main() { int x ,y; // in local scope, this x hides top x while (...) { ... }

}

C Introduction / Basics

8/35

Variable scope

int main() { while (...) { int x; // in (other) local scope ... }

}

C Introduction / Basics

9/35

Type Conversion

long long int

double float

int short







Automatic (implicit) conversion to 'bigger'/larger types Automatic (implicit) conversion from short or int to float and double (possible loss of precision int->float) Otherwise: Loss of precision and explicit cast needed

C Introduction / Basics

10/35

“Strange” conversion #include <stdio.h> int main() { int a, c; float b; a = 2147483647; // max int value b = a; // int -> float c = b; // float -> int printf("Values: %d %f %d\n", a, b, c); return 0; }

Values: 2147483647 2147483648.000000 -2147483648

C Introduction / Basics

11/35

Explicit casting ●

The cast operator permits explicit casting: –



valueInTypeA = (TypeA) valueInTypeB;

Cast from floating point to integer truncates value int myInt; double myDouble = 23.42; myInt = myDouble; // myDouble = (int)myDouble; // myDouble = myInt/2 ; // myDouble = (double)myInt/2; // myDouble = myInt/2.0; //

--> trunc to 23 --> trunc to 23 int.div. 23/2 = 11 flt.div. 23/2=11.5 flt.div. 23/2=11.5

Floating point division, if one or both operands are of type float C Introduction / Basics

12/35

Assignments ●

An assignment statement in C is specified by the operator “=” –





foo = bar + 2;

foo <- bar + 2

Assignments are only possible if –

left-hand side and right-hand side have the same type



right-hand side is a subtype of the left-hand side



right-hand side is casted into a subtype of the left-hand side

C also allows multiple assignment statements –

int a,b,c,d; a = b = c = d = 15;



Handy for initialization, but cryptic otherwise (bad style)



Maybe strange errors: ● ●

int a; double b; a = b = 23.42 != b = a = 23.42;

C Introduction / Basics

13/35

Arithmetic Operations ●

C knows the following arithmetic operations: –

+

Addition

x = 2 + 3;



-

Subtraction

x = 2 – 3;



*

Multiplication x = 2 * 3;



/

Division

x = 2 / 3;



%

Modulo

x = 2 % 3;



Division is integer iff both operand types are int



Modulo means reminder of the division (5%3 = 2)

C Introduction / Basics

14/35

Arithmetic shorthands ●

Assignments which assign one operand can be compressed –

x = x OP y

x OP= y

Short Form Translation += x += y; x = x + y; -= x -= y; x = x – y; *= x *= y; x = x * y; /= x /= y; x = x / y; %= x %= y; x = x % y;

C Introduction / Basics

15/35

Increment & Decrement ●



Another short hand for +1 and -1 –

x = x + 1;

x++;



x = x – 1;

x--;

Prefix and postfix possible: –

x++ vs. ++x



y = x++;

y = x; x = x + 1;



y = ++x;

x = x + 1; y = x;



x++ returns the current value of x and then increments x



++x increments the value of x and then returns x

Be aware of the difference!

C Introduction / Basics

16/35

Boolean Logic ●

C uses integers to represent boolean results –

false

(int)0



true

(int)(any other value)



boolean type was introduced in C99

Operator Short Form Example == foo == 23 equal != foo != bar not equal > 23 > 42 greater < 23 < 42 smaller >= 10 >= 9 greater or eq. <= 10 <=10 smaller or eq.

C Introduction / Basics

17/35

Logic Operators ●

Boolean expressions can be linked and evaluated together –

AND – Both operands need to be true ( a && b )



OR – One of the operands needs to be true ( a || b )



NOT – The operand is negated ( !a )



Precedence: ! > && > || ●

Same as in algebraic calculations Operands a b F F F T T F T T

C Introduction / Basics

AND a && b F F F T

OR NOT a || b !a F T T T T F T F

18/35

Lazy Evaluation ●

C is lazy at the evaluation of logic comparisons –



(( bool1 ) && ( bool2 )) –



bool1 && xx++

bool2 is only evaluated if bool1 is true

(( bool1 ) || ( bool2 )) –



Careful with side effects!

bool2 is only evaluated if bool1 is false

int bool = ( a == 0 ) && ( ++a ); –

a is only incremented if it was 0 beforehand



if a = 0 -> bool = 1, a = 1



if a = 1 -> bool = 0, a = 1



if a = 2 -> bool = 0, a = 2

C Introduction / Basics

19/35

Bitwise logical operators ●

Every bit in a variable is examined and changed –

different from logical operators that use all bits to represent true or false Operator ~ << >> & ^ |



Name not shift left shift right AND XOR OR

Example ~0011 => 1100 1011<<2 => 1100 1011>>2 => 0010 10 & 11 => 10 10 ^ 11 => 01 10 | 11 => 11

Precedence: ~, <<, >>, &, ^, |

C Introduction / Basics

20/35

I/O – Input and Output ●

The printf(...) function writes to the console –

use #include <stdio.h> to include the header file



printf("Hello World!\n");



takes at least one argument (more later)



Strings must be contained in double quotes ( "<String>" )



Strings can contain ANSI-C escape sequences ●

\n (newline)



\t (tab stop)



\" (double quote)



\\ (backslash)

C Introduction / Basics

21/35

Formatted Output ●



Not only strings can be printed to the console! The first argument to printf is a String that may contain special format characters (with leading %)



printf(char*, arg1, arg2, ..., argn);



Format characters: Token %d, %i %o %x, %X %u %c %s %f %e, %E %p %%

C Introduction / Basics

Type int int int int char char* double double pointer none

Output Decimal Octal Hexadecimal Unsigned Character String (until \0) Decimal Scientific (2.3e10) Memory Address Character '%' 22/35

Output example #include <stdio.h> int main() { int myInt = 23; float myFloat = 42.23; printf("myInt = %d\n", myInt); printf("myFloat = %f\n", myFloat); printf("&myInt = %p\n", &myInt); return 0; }

myInt = 23 myFloat = 42.230000 &myInt = 0xbffeefdc

C Introduction / Basics

23/35

Reading from std. input ●

scanf is very similar to printf –

First argument is a format string



Other arguments are pointers to variables



scanf reads a string, parses it according to the format string and writes the interpreted data to the arguments



scanf(char*, &arg1, &arg2, ..., &argn);



&arg1 is the pointer to the memory location where arg1 is ●

Remember: C uses call by value (so passing arg1 would not work)!



The format string can contain the same characters as the printf format string



scanf("%d", &anInt); ●

reads an integer from the command line and saves it to the address of anInt

C Introduction / Basics

24/35

if Statement ●

if (boolean_expression) statement; –

statement is executed if boolean_expression is true



optional else block if statement is not true



if there are multiple statements, then a statement block can be used ●

statement = '{' stmt1; stmt2; ... stmtn; '}'

yes

if (foo==bar) { foo = 15; printf(“equals”); } else printf(“does not equal”);

true?

stmt

no

stmt

... C Introduction / Basics

25/35

Dangling-Else Problem if (a == 1) if (b == 1) a = 42; else b = 42;







if (a == 1) { if (b == 1) a = 42; } else { b = 42; }

C Introduction / Basics





C does not care about indentation To which “if” does the else part belong? Compiler maps “else” to the closest “if” without “else” Use statement blocks to make it explicit One of the most common mistakes!

26/35

Shorthand if-assignment ●

Often an assignment is directly determined by the if condition

if (foo>bar) max = foo; else max = bar;



max = (foo>bar) ? foo : bar;

(condition) ? expression1 : expression2; –

Is itself evaluated to an expression



Can be used inline



Handy for e.g. return values



Can be very cryptic if used inappropriately

C Introduction / Basics

27/35

while loop ●

Executed if and as long as the condition is true –

Loop is executed 0 or more times



Condition is an expression that evaluates to a boolean

while (condition) { stmt1; stmt2; ... } ...

true?

no

yes stmts

... C Introduction / Basics

28/35

for loop ●

For loops have at least 4 statements –

Initial statement (executed before loop is entered)



Loop condition (evaluated at loop head)



Loop statement (executed at end of loop)



Loop body (executed if loop condition is true)



for (init_stmt; loop_condition; loop_stmt) loop_body; ●

loop_body can be replaced by a statement block

#include <stdio.h> int main() { int i, sum=0; for (i=0; i<10; i++) { sum+=i; printf("i: %d, sum: %d\n", i, sum); } }

C Introduction / Basics

29/35

for <=> while ●

Every while loop can be rewritten as a for loop and vice versa

init; while (cond) { stmt1; stmt2; ... end; } ...

C Introduction / Basics

for (init; cond; end) { stmt1; stmt2; ... } ...

30/35

do .. while loop ●

Executed once and as long as the condition is true –

Loop is executed 1 or more times



Condition is an expression that evaluates to a boolean

do { stmt1; stmt2; ... } while (condition); ...

stmts yes true?

no

... C Introduction / Basics

31/35

break & continue ●



break can be used to 'break out' of a loop to the next higher scope continue immediately jumps to the beginning of the loop (without evaluating the rest)

#include <stdio.h> int main() { int x; for ( x=0; x<=100; x++) { if (x%2) continue; printf("%d\n", x); } }

#include <stdio.h> int main() { int t; for ( ; ; ) { scanf("%d", &t); if ( t==10 ) break ; } printf("Inf. loop ended\n"); }

http://www.le.ac.uk/cc/tutorial/c/ccccif.html

C Introduction / Basics

32/35

switch ●



if is good for 2 alternatives, but does not scale C has the switch statement to select between multiple statements –

After a test the program continues at the corresponding case



The default is executed if no match is found (and nothing is executed if there is no default) switch (expression) { case constant1: stmt1; case constant2: stmt1; case constant3: stmt1; default: stmt1; stmt2; }

C Introduction / Basics

stmt2; ... break; stmt2; ... break; stmt2; ... break; ...

33/35

Duff's Device ●

Method for (handmade, compiler independent) loop unrolling for (count=NRITR; count>0; count--) mul *= count;

count = NRITR; switch (count % 8) /* count > 0 assumed */ { case 0: do { mul *= count--; case 7: mul *= count--; case 6: mul *= count--; case 5: mul *= count--; case 4: mul *= count--; case 3: mul *= count--; case 2: mul *= count--; case 1: mul *= count--; } while ((count -= 8) > 0); }

http://en.wikipedia.org/wiki/Duff's_device C Introduction / Basics

34/35

Questions

? C Introduction / Basics

35/35

Related Documents

C Intro2
May 2020 2
Imuno Intro2
November 2019 15
Ch-01-intro2
December 2019 5
Jeni-intro2-bab10-jaringan
November 2019 28