function_c

function_c

return-type function-name ( parameters )
{
    declarations
    statements
}

return typ := the type of data the function takes place of (for lack of a better word, despite being a circular definition return)

parameter := the variables in the function initialisation

the return type

The function may not return arrays

In c89 if the return type is omitted, the function is assumed to be of type int

In c99 the return type must be there, otherwise it is illegal

the body of the function and mixing declarations and statements

In c99 you can mix declarations and statements, as long as variables are declared before use.

In c89 you cannot mix declarations and statements, and statments must come first.

function declarations

The reason why we need function declarations, is so because C is sequential, and so that we don’t need to define the function before calling it.

This is technically a function protoype.

c89 will implicitly declare and int returning function if one hasn’t been defined in the sequence point, but in c99 either a declaration or a definition must be present.

argument conversions

If the compiler has encountered a prototype prior to the call, the value is implicitly converted to the prototypes parameter as if by assignment.

Else if the compiler has not encountered a prototype prior the the call, then it performs default argument promotions. float converts to double, integral promotions occur see type_conversions

static

compound literal

An unnamed [[array___20240710_140429|array]] created on the fly.

total = sum_array((int[]){3, 0, 3, 4, 1}, 5);
total = sum_array((int[]){3, 0, 3, 4, 1}, 5); // expressing the length of the array explicitly
total = sum_array(( const int[]){3, 0, 3, 4, 1}, 5); //the array is now read only

This is an lvalue, so the values of its literal can be changed.

return statement

return statements can be a bit more exotic.

return n >= 0 ? n : 0;

functions can return a pointer

int *max(int *a, int *b){
    if (*a > *b){
        return a;
    } else {
        return b;
    }
}

but do not return an automatic variable as the pointer will be freed after use, so the pointer is invalid.

If a non-void function reaches the end of the function without returning anything, what happens?

The behaviour is undefined if the value returned by the function is attempted to be used.

tags

c

backlinks