Functions

  • Code blocks (code patterns) used to organize code

  • Fundamental building blocks of code

Purpose:

  • Readability (modularity)

  • Reusability

Function declaration (Prototype)

return_type function_name(parameters)

It is defined outside the function, before the function definition

  • A promise to the compiler ("I promise that function_name exists") ➡️ No compilation errors

  • The linker matches the prototypes to the actual definitions

Function Definition

return_type function_name(parameters)
{
    body
    return return_value;
}
  • return_type

    • indicates the type returned by the function (an array cannot be returned)

    • return_value needs to have return_type type

  • parameters: indicates the types of variables to be passed to the function

Automatic local variables All variables declared inside a function are:

  • LOCAL (with respect to scope) They are visible only within the function

  • AUTOMATIC (in terms of memory management)

    • Memory is allocated for the variables

    • It is freed when the function exits

Function Invocation

function_name(arguments)

arguments are passed by value and are copied New variables are created inside the function (initialized with the values of the arguments)

Arrays as function parameters

If a vector is passed as a parameter, it is treated as the pointer associated with the vector

  • The pointer to the array is passed by value (the array itself is not copied, only the pointer)

  • I can directly access the elements of the array passed as a parameter

Example:

int size(int a[])
{
	int size;
	size=sizeof(a)/sizeof(a[0]);
	return size;
}

It does not return the array length as requested:sizeof(a): size of the pointer variable, not the array length.sizeof(a[0]): size of the first element of the array (using the indexing operator, which is also valid for pointers)

Last updated