a unique name, a list of parameters in parentheses, and various statements. a function with non

Upload: bujareta

Post on 30-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    1/16

    Jump statements transfer control unconditionally. There are four types of jump statements

    in C: goto, continue, break, and return.

    The goto statement looks like this:

    goto ;

    The identifier must be a label (followed by a colon) located in the current function.

    Control transfers to the labeled statement.

    A continue statement may appear only within an iteration statement and causes control to

    pass to the loop-continuation portion of the innermost enclosing iteration statement. That

    is, within each of the statements

    while (expression)

    {

    /* ... */cont: ;

    }

    do

    {

    /* ... */

    cont: ;} while (expression);

    for (expr1; expr2; expr3) {

    /* ... */

    cont: ;

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    2/16

    }

    a continue not contained within a nested iteration statement is the same as goto cont.

    The break statement is used to end a for loop, while loop, do loop, or switch statement.Control passes to the statement following the terminated statement.

    A function returns to its caller by the return statement. When return is followed by anexpression, the value is returned to the caller as the value of the function. Encountering

    the end of the function is equivalent to a return with no expression. In that case, if the

    function is declared as returning a value and the caller tries to use the returned value, theresult is undefined.

    [edit] Storing the address of a label

    GCC extends the C language with a unary && operator that returns the address of a label.

    This address can be stored in a void* variable type and may be used later in a goto

    instruction. For example, the following prints "hi " in an infinite loop:

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    3/16

    void *ptr = &&J1;

    J1: printf("hi ");goto *ptr;

    This feature can be used to implement a jump table.[edit] Functions

    [edit] Syntax

    A C function definition consists of a return type (void if no value is returned), a unique

    name, a list of parameters in parentheses, and various statements. A function with non-

    void return type should include at least one return statement.

    functionName( )

    {

    return ;}

    where variables is a comma separated list of parameter declarations,

    each item in the list being a data type followed by an identifier: data-type variable, data-

    type variable,.... If there are no parameters the parameter-list may left empty or optionally

    be specified with the single word void. It is possible to define a function as taking avariable number of parameters by providing the ... keyword as the last parameter instead

    of a data type and variable name. A commonly used function that does this is the standard

    library function printf, which has the declaration:

    int printf (const char*, ...);

    Manipulation of these parameters can be done by using the routines in the standard

    library header .

    [edit] Function Pointers

    A pointer to a function can be declared as follows:

    (*functionName)();

    The following program shows use of a function pointer for selecting between addition

    and subtraction:

    #include

    int (*operation)(int x, int y);

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    4/16

    int add(int x, int y)

    {return x + y;

    }

    int subtract(int x, int y)

    {return x - y;

    }

    int main(int argc, char* args[])

    {

    int foo = 1, bar = 1;

    operation = add;

    printf("%d + %d = %d\n", foo, bar, operation(foo, bar));

    operation = subtract;printf("%d - %d = %d\n", foo, bar, operation(foo, bar));

    return 0;

    }

    [edit] Global structure

    After preprocessing, at the highest level a C program consists of a sequence ofdeclarations at file scope. These may be partitioned into several separate source files,

    which may be compiled separately; the resulting object modules are then linked alongwith implementation-provided run-time support modules to produce an executable image.

    The declarations introduce functions, variables and types. C functions are akin to the

    subroutines of Fortran or the procedures of Pascal.

    A definition is a special type of declaration. A variable definition sets aside storage and

    possibly initializes it, a function definition provides its body.

    An implementation of C providing all of the standard library functions is called a hostedimplementation. Programs written for hosted implementations are required to define aspecial function called main, which is the first function called when execution of the

    program begins.

    Hosted implementations start program execution by invoking the main function, whichmust be defined following one of these prototypes:

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    5/16

    int main() {...}

    int main(void) {...}

    int main(int argc, char *argv[]) {...}

    (int main(int argc, char **argv) is also allowed). The first two definitions

    are equivalent (and both are compatible with C++). It is probably up to individual

    preference which one is used (the current C standard contains two examples of main()and two of main(void), but the draft C++ standard uses main()). The return value of main

    (which should be int) serves as termination status returned to the host environment. The

    C standard defines return values 0 and EXIT_SUCCESS as indicating success andEXIT_FAILURE as indicating failure. (EXIT_SUCCESS and EXIT_FAILURE are

    defined in ). Other return values have implementation defined meanings; for

    example, under Linux a program killed by a signal yields a return code of the numericalvalue of the signal plus 128.

    A minimal C program would consist only of an empty main routine:

    int main(){}

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    6/16

    The main function will usually call other functions to help it perform its job.

    Some implementations are not hosted, usually because they are not intended to be used

    with an operating system. Such implementations are called free-standing in the C

    standard. A free-standing implementation is free to specify how it handles programstartup; in particular it need not require a program to define a main function.

    Functions may be written by the programmer or provided by existing libraries. Interfacesfor the latter are usually declared by including header fileswith the #include

    preprocessing directiveand the library objects are linked into the final executable

    image. Certain library functions, such as printf, are defined by the C standard; these arereferred to as the standard library functions.

    A function may return a value to caller (usually another C function, or the hostingenvironment for the function main). The printf function mentioned above returns how

    many characters were printed, but this value is often ignored.[edit] Argument passing

    In C, arguments are passed to functions by value while other languages may pass

    variables by reference. This means that the receiving function gets copies of the values

    and has no direct way of altering the original variables. For a function to alter a variablepassed from another function, the caller must pass its address (a pointer to it), which can

    then be dereferenced in the receiving function (see Pointers for more info):

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    7/16

    void incInt(int *y)

    {(*y)++; // Increase the value of 'x', in main, by one

    }

    int main(void)

    {

    int x = 0;incInt(&x); // pass a reference to the var 'x'

    return 0;

    }

    The function scanf works the same way:

    int x;

    scanf("%d", &x);

    In order to pass an editable pointer to a function you have to pass a pointer to that pointer;its address:

    #include

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    8/16

    #include

    void setInt(int **p, int n)

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    9/16

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    10/16

    {*p = malloc(sizeof(int)); // allocate a memory area, saving the pointer in the

    // location pointed to by the parameter "p"

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    11/16

    if (*p == NULL)

    {

    perror("malloc");exit(EXIT_FAILURE);

    }

    // dereference the given pointer that has been assigned an address

    // of dynamically allocated memory and set the int to the value of n (42)

    **p = n;}

    int main(void)

    {int *p; // create a pointer to an integer

    setInt(&p, 42); // pass the address of 'p'

    free(p);return 0;

    }

    int **p defines a pointer to a pointer, which is the address to the pointer p in this case.

    [edit] Array parameters

    Function parameters of array type may at first glance appear to be an exception to C's

    pass-by-value rule. The following program will print 2, not 1:

    #include

    void setArray(int array[], int index, int value)

    {array[index] = value;

    }

    int main(void)

    {

    int a[1] = {1};setArray(a, 0, 2);printf ("a[0]=%d\n", a[0]);

    return 0;

    }

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    12/16

    However, there is a different reason for this behavior. In fact, a function parameter

    declared with an array type is treated almost exactly like one declared to be a pointer.

    That is, the preceding declaration of setArray is equivalent to the following:

    void setArray(int *array, int index, int value)

    At the same time, C rules for the use of arrays in expressions cause the value of a in the

    call to setArray to be converted to a pointer to the first element of array a. Thus, in fact

    this is still an example of pass-by-value, with the caveat that it is the address of the firstelement of the array being passed by value, not the contents of the array.

    [edit] Miscellaneous

    [edit] Reserved keywords

    The following words are reserved, and may not be used as identifiers:

    auto

    _Boolbreak

    casechar

    _Complex

    const

    continuedefault

    do

    doubleelse

    enum

    externfloat

    for

    goto

    if_Imaginary

    inline

    intlong

    register

    restrict

    return

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    13/16

    short

    signed

    sizeof

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    14/16

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    15/16

  • 8/9/2019 A Unique Name, A List of Parameters in Parentheses, And Various Statements. a Function With Non

    16/16