Skip to main content
C Programming

Encapsulating Code with C Functions

By October 10, 2016September 12th, 2022No Comments

Using C FunctionsEvery C program that is to be executable will require a function called main but others functions can be created. C functions encapsulate code, allowing the code to be run and maintained as its own unit. Functions may or may not return data, it is optional.  Writing C functions as we used in the last tutorial, required no return value. We simply set the terminal colour. Turning up the heat a little now we will look at using C functions to convert temperature values and we will be requiring values to be returned.

Convert Centigrade to Fahrenheit Using C Functions


Using C functions we will convert a temperature supplied in Centigrade to a displayed values in Fahrenheit. Keeping both us in Europe happy and you guys on the other side of the pond. Additionally, we could add in another function to convert in the reverse direction. We will keep that for another lesson. We will also need to ensure that we have, firstly, read the data in correctly from the user. User input will always be in the form of a string and we will need numeric data to run calculations.

The Complete Code

#include <stdio.h>
#include <stdlib.h>
float ctof ( int centigrade ) {
  float fahrenheit = (( centigrade * 9)/5)+32;
  return fahrenheit;
}
int main( int argc, char **argv ) {
  long c;
  float ret_f = 0.0;
  char *extra;
  if ( argc > 1 ) {
    c = strtol(argv[1],&extra,10);
    ret_f = ctof(c);
    printf("%ld degrees in C is %.2f degrees F\n",c,ret_f);
    return 0;
  } else {

    printf("You must supply a value\n");
    return 1;
    }
}

The Function

Defining the function happens early on and OUTSIDE of the main function.

float ctof ( int centigrade ) {
  float fahrenheit = (( centigrade * 9)/5)+32;
  return fahrenheit;
}

We allow it to return a floating decimal, (a number with decimal places). The formula is readily available from any google search. The parentheses control the order of the evaluations. The centigrade value is first multiplied by 9  and the result divided by 5. This all happens before 32 is added to the result.

Safely Converting User Data

We want to make sure that if a user types in their life story as an argument to the program, that we do not try to convert the entire input to a numeric value. We do this with the function strtol. This is supplied by the C standard library. Remember not all C functions need to be created by us.

c = strtol(argv[1],&extra,10);

Using this function we can control how much we read and here, we just read in 10 characters. Any extra is discarded into the array extra.

The complete video is shown for you below and I hope you enjoy.