c intro2

Embed Size (px)

Citation preview

  • 8/14/2019 c intro2

    1/35

    C Introduction / Basics 1/35

    Introduction to C

    Part 2: Basics

    C Language TutorialSystem Programming 251-0053

    Fall Semester 08

    Mathias Payer, RZ H11

    mailto:[email protected]:[email protected]
  • 8/14/2019 c intro2

    2/35

    C Introduction / Basics 2/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

  • 8/14/2019 c intro2

    3/35

    C Introduction / Basics 3/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

  • 8/14/2019 c intro2

    4/35

    C Introduction / Basics 4/35

    Variable declaration

    Variables must be declared before they can be used

    Variables are declared at the beginning of the codeblock

    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 Identifier int foo;double bar;char ch;

  • 8/14/2019 c intro2

    5/35

    C Introduction / Basics 5/35

    Initial value & literals

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

    int foo = 4;double xx = 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.4223.42d

    2.3e42 (=2.3 * 1042)

    float: 42.23f

    4.2e-23 (=4.2 * 10-23)

    char: 'c'

  • 8/14/2019 c intro2

    6/35

    C Introduction / Basics 6/35

    Constants

    A constant is a variable that cannot be changed afterits initialisation

    C has the keyword const to tell the Compiler that avalue 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 aconstant is overwritten in the program

    Aliasing can overwrite constants Leads to strange effects (register vs. fetch from memory)

  • 8/14/2019 c intro2

    7/35

    C Introduction / Basics 7/35

    Variable scope

    int x; // in global scope

    int main(){

    while (...) {

    ...

    }

    }

  • 8/14/2019 c intro2

    8/35

    C Introduction / Basics 8/35

    Variable scope

    int x;

    int main(){

    int x ,y; // in local scope, this x hides top x

    while (...) {

    ...

    }

    }

  • 8/14/2019 c intro2

    9/35

    C Introduction / Basics 9/35

    Variable scope

    int main(){

    while (...) {

    int x; // in (other) local scope

    ...

    }

    }

  • 8/14/2019 c intro2

    10/35

    C Introduction / Basics 10/35

    Type Conversion

    long long int

    int

    short

    double

    float

    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

  • 8/14/2019 c intro2

    11/35

    C Introduction / Basics 11/35

    Strange conversion

    #include

    int main() {int a, c;float b;a = 2147483647; // max int valueb = a; // int -> floatc = b; // float -> intprintf("Values: %d %f %d\n", a, b, c);

    return 0;}

    Values: 2147483647 2147483648.000000 -2147483648

  • 8/14/2019 c intro2

    12/35

    C Introduction / Basics 12/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; // --> trunc to 23myDouble = (int)myDouble; // --> trunc to 23myDouble = myInt/2 ; // int.div. 23/2 = 11myDouble = (double)myInt/2; // flt.div. 23/2=11.5myDouble = myInt/2.0; // flt.div. 23/2=11.5

    Floating point division,if one or both

    operands are of typefloat

  • 8/14/2019 c intro2

    13/35

    C Introduction / Basics 13/35

    Assignments

    An assignment statement in C is specified by theoperator =

    foo = bar + 2; foo

  • 8/14/2019 c intro2

    14/35

    C Introduction / Basics 14/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)

    A ith ti h th d

  • 8/14/2019 c intro2

    15/35

    C Introduction / Basics 15/35

    Arithmetic shorthands

    Assignments which assign one operand can becompressed

    x = x OP y x OP= y

    += 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;

    Short Form Translation

    I t & D t

  • 8/14/2019 c intro2

    16/35

    C Introduction / Basics 16/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!

    B l L i

  • 8/14/2019 c intro2

    17/35

    C Introduction / Basics 17/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==

    !=

    > 23 > 42

    < 23 < 42

    >= 10 >= 9

  • 8/14/2019 c intro2

    18/35

    C Introduction / Basics 18/35

    Logic Operators

    Boolean expressions can be linked and evaluatedtogether

    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

    AND OR NOTa b a && b a || b !aF F F F T

    F T F T T

    T F F T F

    T T T T F

    Operands

    Lazy Evaluation

  • 8/14/2019 c intro2

    19/35

    C Introduction / Basics 19/35

    Lazy Evaluation

    C is lazy at the evaluation of logic comparisons

    Careful with side effects!

    (( bool1 ) && ( bool2 ))

    bool2 is only evaluated if bool1 is true

    (( bool1 ) || ( bool2 ))

    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

    bool1 && xx++

    Bitwise logical operators

  • 8/14/2019 c intro2

    20/35

    C Introduction / Basics 20/35

    Bitwise logical operators

    Every bit in a variable is examined and changed

    different from logical operators that use all bits to representtrue or false

    Precedence: ~, , &, ^, |

    Operator Name~ ~0011 => 1100

    1011>>2 => 0010& AND 10 & 11 => 10^ XOR 10 11 => 01| OR 10 | 11 => 11

    Examplenot

    shift left

    shift right

    I/O Input and Output

  • 8/14/2019 c intro2

    21/35

    C Introduction / Basics 21/35

    I/O Input and Output

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

    use #include to include the header file

    printf("Hello World!\n");

    takes at least one argument (more later)

    Strings must be contained in double quotes ( "" )

    Strings can contain ANSI-C escape sequences

    \n (newline)

    \t (tab stop)

    \" (double quote)

    \\ (backslash)

    Formatted Output

  • 8/14/2019 c intro2

    22/35

    C Introduction / Basics 22/35

    Formatted Output

    Not only strings can be printed to the console!

    The first argument to printf is a String that maycontain special format characters (with leading %)

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

    Format characters:

    Type%d, %i

    %o%x, %X

    %u%c

    %s%f%e, %E

    %p%%

    Token Outputint Decimalint Octalint Hexadecimalint Unsigned

    char Character

    char* String (until \0)double Decimaldouble Scientific (2.3e10)pointer Memory Addressnone Character '%'

    Output example

  • 8/14/2019 c intro2

    23/35

    C Introduction / Basics 23/35

    Output example

    #include 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 = 23myFloat = 42.230000&myInt = 0xbffeefdc

    Reading from std input

  • 8/14/2019 c intro2

    24/35

    C Introduction / Basics 24/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 formatstring 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 wouldnot work)!

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

    scanf("%d", &anInt);

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

    if Statement

  • 8/14/2019 c intro2

    25/35

    C Introduction / Basics 25/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 canbe used

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

    if (foo==bar) {foo = 15;printf(equals);

    } else

    printf(does not equal);

    true?

    stmt stmt

    noyes

    ...

    Dangling-Else Problem

  • 8/14/2019 c intro2

    26/35

    C Introduction / Basics 26/35

    Dangling Else Problem

    if (a == 1)if (b == 1)a = 42;

    elseb = 42;

    C does not care aboutindentation

    To which if does the else partbelong?

    Compiler maps else to theclosest if without else

    Use statement blocks to make itexplicit

    One of the most commonmistakes!

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

    } else {b = 42;

    }

    Shorthand if-assignment

  • 8/14/2019 c intro2

    27/35

    C Introduction / Basics 27/35

    Shorthand if assignment

    Often an assignment is directly determined by the ifcondition

    (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

    if (foo>bar)max = foo;

    elsemax = bar;

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

    while loop

  • 8/14/2019 c intro2

    28/35

    C Introduction / Basics 28/35

    e oop

    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?

    stmts

    ...

    no

    yes

    for loop

  • 8/14/2019 c intro2

    29/35

    C Introduction / Basics 29/35

    p

    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 int main(){

    int i, sum=0;for (i=0; i

  • 8/14/2019 c intro2

    30/35

    C Introduction / Basics 30/35

    Every while loop can be rewritten as a for loop andvice versa

    init;while (cond) {stmt1;

    stmt2;...end;

    }...

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

    ...}...

    do .. while loop

  • 8/14/2019 c intro2

    31/35

    C Introduction / Basics 31/35

    p

    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);... true?

    stmts

    ...

    no

    yes

    break & continue

  • 8/14/2019 c intro2

    32/35

    C Introduction / Basics 32/35

    break can be used to 'break out' of a loop to thenext higher scope

    continue immediately jumps to the beginning of theloop (without evaluating the rest)

    #include int main(){

    int x;for ( x=0; x

  • 8/14/2019 c intro2

    33/35

    C Introduction / Basics 33/35

    if is good for 2 alternatives, but does not scale

    C has the switch statement to select betweenmultiple statements

    After a test the program continues at the correspondingcase

    The default is executed if no match is found (and nothing is

    executed if there is no default)

    switch (expression) {case constant1: stmt1; stmt2; ... break;case constant2: stmt1; stmt2; ... break;case constant3: stmt1; stmt2; ... break;default: stmt1; stmt2; ...

    }

    Duff's Device

  • 8/14/2019 c intro2

    34/35

    C Introduction / Basics 34/35

    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);}

    Method for (handmade, compiler independent) loopunrolling

    http://en.wikipedia.org/wiki/Duff's_device

    Questions

    http://en.wikipedia.org/wiki/Duff's_devicehttp://en.wikipedia.org/wiki/Duff's_device
  • 8/14/2019 c intro2

    35/35

    C Introduction / Basics 35/35

    ?