C Course - Variables

download C Course - Variables

of 22

Transcript of C Course - Variables

  • 8/9/2019 C Course - Variables

    1/22

     Variables

  • 8/9/2019 C Course - Variables

    2/22

    Variables introduction

    Variables refer to sections of memory into which

    data are or will be stored. Variables have meaningful names to ease access

    to them: for assigning data (write)

    for retrieving data (read)

    Variables should match size of the data thatshould be stored in them e.g.:

    number 2 requires char type variable (1 byte in size) number 1.9 requires float type variable (4 bytes in size)

  • 8/9/2019 C Course - Variables

    3/22

    Variable NamingConventions

    Rules:

    The first character must be a letter or underscore (NOT recommended).

    After the first character, letters, numbers and the underscore can be used.

    Spaces are NOT allowed.

    C reserved keywords as a whole name are NOT allowed

    Case is significant

    Only the first 31 characters are significant.

    Names should be meaningful or descriptive.

    studentAge or student_age is more meaningful than age, and much moremeaningful than a single letter such as a.

    Spaces are either replaced by the underscore, e.g. account_name or thespace removed and the second name started with an uppercase letter e.g.accountName.

    If you are working as part of a team, then additional naming conventions may berequired.

  • 8/9/2019 C Course - Variables

    4/22

    Declaration vs. Definitionof the variable

    Definition tells the compiler: to allocate memory for the variable (possibly) to initialize its contents to some value.

    Declaration tells the compiler that the variable is defined elsewhere

    For automatic and register variables there isno difference between declaration and

    definition. For global (extern) variables we have

    difference between those two.

  • 8/9/2019 C Course - Variables

    5/22

    Single and multipledeclarations

    Single declarationsint age;

    float amountOfMoney;

    char initial;

    Multiple declarations

    You can repeat the declaration line with a different variable on each line e.gint age;

    int houseNumber;

    but also you can separate the variables by a comma.

    int age, houseNumber, quantity;float distance, rateOfDiscount;

    char firstInitial, secondInitial;

  • 8/9/2019 C Course - Variables

    6/22

  • 8/9/2019 C Course - Variables

    7/22

    Automatic (local) Variables

    Keyword auto

    They are declared at the start of a block of code (block is considered as a codebetween { } )

    Memory is allocated automatically upon entry to a block and freed automatically uponexit from the block.

    C use stack space for local variables.

    They are not automatically initialized and contain random data.

    The scope is local to the block in which they are declared, including any blocksnested within that block. For these reasons, they are also called local variables.

    Direct access (by name) to automatic variables, is not possible outside the definingblock

    By default, storage class of the variable within a block is auto.

    Automatic variables declared with init values are initialized each time the block inwhich they are declared is entered.

    Example: auto int Month;

  • 8/9/2019 C Course - Variables

    8/22

    Register Variables

    Keyword register

    Register variables are a special case of automatic variables

    Normally, the compiler determines what data should be stored in the registers of theCPU at what times.

    For most CPUs, accessing data in memory is considerably slower than accessingdata from registers.

    Variables which are used repeatedly or whose access times are critical, may be

    declared to be of storage class register. Register keyword ''suggests'' to the compiler that particular automatic variables

    should be allocated to CPU registers, if possible.

    The scope of register variables is local to the block in which they are declared.

    Rules for initializations for register variables are the same as for automatic variables.

    Example: register int Day;

  • 8/9/2019 C Course - Variables

    9/22

    Global Variables

    Global variables are accessible from within any block in the code exist for the entire execution of the program.

    Storage class extern meets these

    requirements; Their definition is in a source file, outside any

    function block.

    They are automatically initialized to zero.

  • 8/9/2019 C Course - Variables

    10/22

    External Variables

    Keyword extern (only for declaration !!!)

    Definition has NO storage class specifier( e.g. extern or static) Declaration uses extern storage class specifier – It is done in files

    other than where the variable is defined

    Lifetime is as the lifetime of the entire program

    They are automatically initialized to zero.

    Scope of external variables is global, i.e. the entire source code inthe file following the declarations.

    All functions following the declaration may access the externalvariable by using its name.

    If a local variable is having the same name as extern variable,local variable takes precedence.

    If it is declared inside a function it is visible only inside thatfunction.

  • 8/9/2019 C Course - Variables

    11/22

    External Variables, Yes orNo ?

    In general, it is a good programming practice to avoid use ofexternal variables because

    they destroy the concept of a module function as a ''black box'‘

    any function in the program can access and alter the variable, thusmaking debugging more difficult as well.

    Sometimes external variable significantly simplifies the

    implementation of an algorithm.

    So, external variables should be used

    rarely and with caution !!!

  • 8/9/2019 C Course - Variables

    12/22

    Duplicate Symbols

    What happens if there are two definitions for a symbol when it comes to link time?What if we have:

    int var;appears in each of two or more separate source program files?

    Linker will share a single instance of a whether they wanted toLinker will share a single instance of a whether they wanted to shareshare varvar or not.or not.

    int var = 7 appears in one file and int var = 9; in another

    Linker will reject thisLinker will reject this

    GNU C linker requires each object to be defined once

    EXCEPTION:

    uninitialized variables go in the " common " (or " bss ") section and can bemultiply "defined".

    You can force a variable to be initialized with the -fno-common flag

  • 8/9/2019 C Course - Variables

    13/22

    Static Variables

    Keyword static

    Lifetime is as the lifetime of the entire program They are automatically initialized to zero

    There are:

    Variables declared as static inside a function:

    are initialized only once – in the first function execution

    have the same scope as automatic local variables

    continue to exist even after the block in which they are defined terminates.

    retain value between repeated calls to the same function.

    Variables declared as static at file scope (outside any function definitions): have scope throughout that file ("file scope")

    are initialized only with constants and only once at compile time (of course,assigning other values is possible if variable is not declared as const)

  • 8/9/2019 C Course - Variables

    14/22

  • 8/9/2019 C Course - Variables

    15/22

    Where to declare and (not)initialize variables?

    Variables should always be declared at the start of a

    source file (.c) or function Variables should be initialized as soon as possible, at

    least before they are used.

    The obvious and most sensible time is when they are

    declared, e.g.:

    int count = 0;

    signed char letter =’a’;

    NOTE: Variables shall not be defined inside headerfile (.h)

  • 8/9/2019 C Course - Variables

    16/22

    Type qualifiers

    Volatile - says to compiler: the value of this could change without the programtouching it. This is essential in embedded programming.

    Const - should be used where value of the variable is not going to change. It is alsocommon in function parameter declarations. For example

    static uint8_t func(const uint8_t *name, const uint8_t number);

    What's the difference between:1. const char *p

    2. char const *p

    3. char * const p

    The 1st and the 2nd are the same; they declare a pointer to a constant character (youcan't change value pointed-to by this pointer).

    The 3rd declares a constant pointer to a (variable) character (i.e. you can't changethe pointer).

  • 8/9/2019 C Course - Variables

    17/22

    Constants

    Declaring a constant is a bit like a variable declaration except thevalue cannot be changed.

    The const keyword is to declare a constant, as shown below:

    int const a = 1;

    const int a = 2;

    Note: You can declare the const before or after the type.Choose one and stick to it.

    They are initialized at declaration since they cannot get avalue any other way .

    #define is another more flexible method to define constants in aprogram.

  • 8/9/2019 C Course - Variables

    18/22

  • 8/9/2019 C Course - Variables

    19/22

    Variable Length Arrays(VLA)

    OLD, most common way:void f(int m, int n)

    {float *a = malloc(m * n * sizeof(float));

    for (i = 0; i < m; ++i)

    for (j = 0; j < n; ++j)

    a[i*n + j] = 1.0;

    }

    New, VLA way:void f(int m, int n)

    {

    float a[m][n];

    for (i = 0; i < m; ++i)for (j = 0; j < n; ++j)

    a[i][j] = 1.0;

    }

  • 8/9/2019 C Course - Variables

    20/22

    Variable Length Arrays(VLA)

    Example in which VLA is used to simplify the code:

    FILE* concat_fopen (char *s1, char *s2, char *mode)

    {

    char str[strlen (s1) + strlen (s2) + 1];

    strcpy (str, s1);

    strcat (str, s2);

    return fopen (str, mode);

    }

  • 8/9/2019 C Course - Variables

    21/22

    Variable Length Arrays(VLA)

    VLA allows:

    bounds of an array can be a run-time expression permits pointers arithmetic

    sizeof operator is evaluated at run time

    VLA rules: must be an local (automatic) variable of a block,

    cannot be declared at file scope.

    cannot have static or extern storage class.

    cannot be a member of a struct or union.

    cannot be initialized.

  • 8/9/2019 C Course - Variables

    22/22

    Variable Length Arrays(VLA)

    Advantages

    Fast: adjusting the stack pointer and/or the frame pointer wouldhave been done anyway so the init cost of a VLA is nearly 0.

    Easy: a simple definition, no pointer to initialize, to check to freeand no risk of memory leaks.

    Readable : it's really a simple concept, so less likely to introduce

    subtle bugs.

    Drawbacks

    Size limited: with the stack size, the stack can blow up.

    Buffer overflows are a bit more serious than on heap memory Portability: not all compilers implement it