Advanced C Course – Class 4

Structured programming

In C it is good practice to break code into functions and group them into modules.

The paradigm of Structured Programming consists of identifying different functionalities and separating them into functions, thus avoiding having a very extensive code continuously because it makes its modification and maintenance very difficult.

Once the different functions have been defined, they can be grouped into modules or files so that there is a tendency to have sets of functions that deal with the same topic or concept.

Variable scope

In C there is the concept of the scope of a variable

The scope refers to the visibility of a variable to define in which area of ​​the program it can be used.

In C we can define code blocks by enclosing it between {. }

Variables defined within a block can only be used within that block and will not be visible outside of it.

These are the local variable calls that the compiler creates when starting a block and are automatically destroyed at the end of the block.

Global variables are those that are defined in a module and that are visible in all the functions created in that module.

Static variables are local variables defined in a function that maintain their value between different calls to the function.

 

Defining functions

A function can be defined in the form

Return name (parameters)

Return is the value that the function will return and can be a data type (int, float …) or void that is used to indicate that it does not return any value.

Name is the identifier of the function

Parameters is a comma separated list of variables that we will pass to the function.

E.g

float Calculate_Iva (float price, float vat)

Parameter passing by value

The most common way to pass parameters to a function is to pass them by value.

Constants or variables are passed that will not change value in the execution of the function.

float CalculateVAT (float price, float vat)

{

return price * vat / 100;

)

int main ()

(

float iva;

iva = CalculateVAT (1000, 21);

)

Parameter passing by reference

If we want a parameter of a function to be modified inside the function and return the modified value, the parameter can be used by reference.

In this case, instead of passing the value, a pointer is passed

E.g

float CalculateVAT (float price, float vat, float * pvp)

{

float pvat;

pvat= price * vat / 100;

* pvp = price + pvat;

return pvat;

)

int main ()

(

float vat, pvp

vat= CalculateVAT (1000, 21, & pvp);

)

This type of parameter passing is usually used when more than one value must be returned in the function.

 

Leave a Reply

Your email address will not be published. Required fields are marked *