C C

Your First C Program: A Delivery Fee Calculator and How to Read What gcc Tells You

Dima Noi 17, 2026

Introduction

The first C program most people write prints a greeting and works on the first try. That teaches almost nothing, because the hard part of C at the start is not the syntax. It is the conversation with the compiler: understanding what gcc did to your file, why it refused it, why it accepted something wrong, and what its long, oddly formatted messages are actually saying.

In this tutorial we will write a small program that calculates a courier's delivery fee, and we will break it on purpose several times. We will see a program that compiles cleanly and still prints the wrong number, a compiler error that points at the wrong line, a warning that only appears when you ask for it, and an error caused by nothing more than the order of two functions in the file. Each time we will read the message field by field and fix the cause, not the symptom.

I will assume you are working in the C/C++ sandbox on Bytestark and that your terminal starts in /home/coder/learning, where we will create every file. You do not need any previous C experience, only the ability to type a command in a terminal.


Background

C is a compiled language. The file you write, fee.c, is plain text meant for a tool to read. That tool is gcc, the GNU C compiler, and its job is to turn your text into an executable: a file of machine instructions the processor runs directly. You never run fee.c itself.

gcc does its work in three stages, and knowing them makes every later error easier to place:

  • The preprocessor handles the lines that start with #. #include <stdio.h> means "paste the contents of the file stdio.h here", and that file tells the compiler which input/output functions exist.
  • The compiler translates the expanded text into machine code and checks that every name you use was declared and every value has a sensible type. Its product is an object file (.o), which is machine code that cannot run yet.
  • The linker joins your object file with the standard library code your program calls, such as the code behind printf, and writes the final executable.

Every value in C has a type that you state when you create a variable. In this tutorial we need two of them: int holds whole numbers (12, -3, 0) and double holds numbers with a fractional part (0.40, 8.30). The type decides how the value is stored and how arithmetic on it behaves, and that turns out to matter a great deal.

Finally, every program starts in a function called main. When main finishes, it returns an integer to the operating system called the exit status: 0 means "everything went fine" and any other number means something failed.


Practical Scenario

A small city courier cooperative charges for each delivery with a simple rule: a base fee of 3.50 EUR plus 0.40 EUR for every kilometre driven. Riders see the fee on their phone before they accept a job, and the same number goes onto the customer's receipt.

Right now one of the dispatchers works the fees out by hand. The cooperative wants a tiny program that does it instead, and they want it to be right, because a fee that is too low comes out of the rider's pocket and a fee that is too high gets the cooperative a complaint. A 12 km delivery should cost 3.50 + 12 × 0.40 = 8.30 EUR. That is the number we will hold the program to.

The program is small enough to fit on one screen, which makes it the perfect place to learn how C and its compiler behave before the programs get bigger. Every mistake we make here is a mistake people make in real code, just easier to see.


The Problem

Here is the first version a beginner might write. It stores the distance, works out the price per kilometre as "2 divided by 5" (which is 0.40), adds the base fee, and prints the result. Watch the fee it prints.

Create the file:

touch fee.c


Put this in it:

#include <stdio.h>

int main(void) {
    int distance_km = 12;
    double per_km = 2 / 5;
    double fee = 3.50 + distance_km * per_km;

    printf("Distance: %d km\n", distance_km);
    printf("Delivery fee: %.2f EUR\n", fee);
    return 0;
}


Build it and run it:

gcc -o fee fee.c && ./fee


Distance: 12 km
Delivery fee: 3.50 EUR


The program compiled without a single message and ran without crashing, yet the fee is 3.50 EUR instead of 8.30 EUR. The rider would be paid nothing for the 12 kilometres they drove.

Let's read the program before we fix it. int distance_km = 12; creates a variable of type int named distance_km and stores 12 in it. double per_km = 2 / 5; is meant to store 0.40. double fee = 3.50 + distance_km * per_km; computes the fee; multiplication happens before addition, exactly as in school arithmetic. The two printf calls print the results, and return 0; reports success to the operating system.

The fee came out as exactly the base fee, which means distance_km * per_km was 0, which means per_km must be 0. The compiler did not complain because, as far as C is concerned, nothing is wrong: the line does exactly what the language says it should. That is the most important lesson of this tutorial, and we will come back to it. "It compiles" only means the text is valid C. It says nothing about whether the program is correct.

Before we fix the arithmetic, though, let's understand the command we just typed, because every section after this one uses it.


What gcc Did With fee.c

The command gcc -o fee fee.c && ./fee is really two commands joined together. Let's take it apart.

  • gcc runs the compiler, with all three stages, on the file named at the end.
  • -o fee names the output file fee. Without -o, gcc calls the executable a.out, and every program you build in the same folder overwrites the previous one.
  • fee.c is the input, the text file we wrote.
  • && is a shell operator that means "run the next command only if this one succeeded". If compilation fails, you see the errors and the old fee is not run, so you never mistake an outdated program for your new one.
  • ./fee runs the new executable. The ./ means "the file called fee in this folder". Without it, the shell looks for a command named fee in its list of system folders and does not find one.

You can watch the three stages one by one. Ask gcc to stop after preprocessing with -E, which prints the expanded text instead of compiling it, and count the lines:

gcc -E fee.c | wc -l


816


Our 11 lines became 816. Those extra lines are the contents of stdio.h, pasted in by #include. Search them for printf:

gcc -E fee.c | grep "int printf"


extern int printf (const char *__restrict __format, ...);


This is a declaration: a line that tells the compiler a function named printf exists, that it returns an int, and that it takes a format string followed by any number of other values (that is what the ... means). It is not the code of printf. That code lives in the C standard library, already compiled. The header only gives the compiler enough information to check your calls. Remember this, because in the last section of this tutorial we will hit an error that comes from a missing declaration.

Now stop after the compiler stage with -c, which produces an object file and skips linking:

gcc -c fee.c && ls -1


fee
fee.c
fee.o


ls -1 lists the folder one name per line. fee is the executable from our first build, and fee.o is new. It contains the machine code for our main, plus a note that says "this code calls printf, which is somewhere else". Try running it:

./fee.o


bash: ./fee.o: Permission denied


The operating system refuses, because an object file is not a complete program. The linker supplies the missing piece:

gcc -o fee fee.o && ./fee


Distance: 12 km
Delivery fee: 3.50 EUR


Given an .o file instead of a .c file, gcc skips straight to the linker, which finds the compiled printf in the standard library and writes a complete executable. The output is the same as before, wrong fee included, because nothing about the program changed. We only ran the stages by hand.

One more thing came back from the run, even though we did not see it: the exit status. The shell keeps it in a variable called $?. Print it right after running the program:

./fee; echo $?


Distance: 12 km
Delivery fee: 3.50 EUR
0


That 0 is the value of return 0; at the end of main. Scripts, build tools and the && operator all read this number to decide whether a program succeeded.

Try it: Change return 0; to return 3;, rebuild with gcc -o fee fee.c, and run ./fee; echo $?. Before you run it, predict the last line. You should see 3, because the exit status is exactly the number main returns. Then put return 0; back.


Why 2 / 5 Is 0 in C

Now for the wrong fee. The suspicious line is this one:

double per_km = 2 / 5;


It looks like it stores 0.40, but C evaluates the right-hand side first, on its own, before it thinks about the variable on the left. 2 and 5 are both written without a decimal point, so both are int values. When both sides of / are int, C performs integer division: it divides and throws away the fractional part. Two divided by five is 0.4, and throwing away the .4 leaves 0.

Only after the division is finished does C look at the left side, see that the variable is a double, and convert the int result 0 into the double 0.0. The conversion cannot bring back a fraction that was already discarded. So per_km is 0.0, distance_km * per_km is 0.0, and the fee is just the base fee.

The fix is to make sure the division never happens in integers. The simplest and clearest way is to write the price as it is:

double per_km = 0.40;


Replace that line in fee.c, so the file looks like this:

#include <stdio.h>

int main(void) {
    int distance_km = 12;
    double per_km = 0.40;
    double fee = 3.50 + distance_km * per_km;

    printf("Distance: %d km\n", distance_km);
    printf("Delivery fee: %.2f EUR\n", fee);
    return 0;
}


Build and run it:

gcc -o fee fee.c && ./fee


Distance: 12 km
Delivery fee: 8.30 EUR


The fee is now 8.30 EUR, the number we calculated by hand. 0.40 has a decimal point, so it is a double literal and never passes through integer arithmetic.

You might be wondering why distance_km * per_km works, when distance_km is an int. When an arithmetic operator gets one int and one double, C first converts the int to double, then does the arithmetic in double. So 12 * 0.40 becomes 12.0 * 0.40, which is 4.80, and nothing is lost. Integer division only bites when both sides are integers.

Now that the numbers are right, let's read the two printf calls properly. The first argument of printf is a format string: text to print, with placeholders that start with %. Each placeholder is replaced by the next argument in order.

  • %d prints an int in decimal. It is replaced by distance_km, so we see 12.
  • %.2f prints a double. The f means "fixed-point number", and .2 means "exactly two digits after the decimal point", which is what money needs. Without .2, printf uses six digits and we would see 8.300000.
  • \n is not a placeholder. It is an escape sequence for the newline character. Without it the next printf would continue on the same line.

Try it: Change the price line to double per_km = (double)(2 / 5);, rebuild and run. Before you run it, decide: does converting to double rescue the fee? It does not. You will still see 3.50 EUR, because the parentheses make 2 / 5 happen first, in integers, and only the result 0 is converted. Then try double per_km = 2.0 / 5; and you get 8.30 EUR again, because one double operand is enough to make the whole division fractional. Leave the file with 0.40.


Reading a Compiler Error

So far gcc has said nothing at all. Most of the time, though, it will have something to say, and beginners lose hours to messages they do not know how to read. Let's produce two errors on purpose.

First, misspell a variable name. In the fee line, change distance_km to distance_kn:

    double fee = 3.50 + distance_kn * per_km;


gcc -o fee fee.c && ./fee


fee.c: In function ‘main’:
fee.c:6:25: error: ‘distance_kn’ undeclared (first use in this function); did you mean ‘distance_km’?
    6 |     double fee = 3.50 + distance_kn * per_km;
      |                         ^~~~~~~~~~~
      |                         distance_km
fee.c:6:25: note: each undeclared identifier is reported only once for each function it appears in


Every gcc message has the same skeleton, so let's take the main line apart once.

  • fee.c: In function ‘main’: is context. It names the file and the function where the problem is.
  • fee.c:6:25: is the location: file fee.c, line 6, column 25. Column 25 is where the d of distance_kn sits.
  • error: is the severity. An error means gcc refused to produce an executable. Because of that, && did not run ./fee.
  • ‘distance_kn’ undeclared (first use in this function) is the actual complaint. The compiler reached a name it has never been told about. C requires every variable to be declared, with its type, before it is used.
  • did you mean ‘distance_km’? is a suggestion. gcc noticed a declared name that differs by one letter.

The next two lines repeat line 6 of your file and put ^~~~~~~~~~~ under the exact characters it is complaining about, and the line under that shows the suggested replacement. The final note: explains that if you used distance_kn five more times in main, you would still get only this one error, so you are not buried under duplicates.

Fix the name back to distance_km. Now make a different mistake: delete the semicolon at the end of the per_km line, so that line 5 reads double per_km = 0.40 with nothing after it.

gcc -o fee fee.c && ./fee


fee.c: In function ‘main’:
fee.c:6:5: error: expected ‘,’ or ‘;’ before ‘double’
    6 |     double fee = 3.50 + distance_km * per_km;
      |     ^~~~~~
fee.c:9:40: error: ‘fee’ undeclared (first use in this function)
    9 |     printf("Delivery fee: %.2f EUR\n", fee);
      |                                        ^~~
fee.c:9:40: note: each undeclared identifier is reported only once for each function it appears in


The semicolon is missing from line 5, but the error points at line 6. That is not a bug in gcc. C ignores line breaks, so to the compiler the text reads double per_km = 0.40 double fee = ... as one long statement. It only discovers the problem when it reaches the word double on line 6, which cannot follow 0.40, and it reports the spot where it got confused: "expected , or ; before double".

This gives you a reliable habit. When an error says "expected something before X", look at the end of the line before X.

The second error is a consequence of the first. Because the statement on line 6 was swallowed, the variable fee was never declared, so line 9 cannot use it. This is common: one real mistake produces several errors further down. Always fix the first error and compile again before reading the rest.

Put the semicolon back and rebuild, and you are back to Delivery fee: 8.30 EUR.

Try it: Delete the very last } of the file, the one that closes main, and rebuild. Predict which line gcc will complain about. It reports fee.c:10:5: error: expected declaration or statement at end of input, pointing at return 0;, because the compiler only discovers the missing brace when the file runs out while main is still open. Put the brace back.


Warnings: When gcc Builds Your Mistake Anyway

An error stops the build. A warning does not: gcc reports something suspicious and then produces the executable anyway. Some warnings are on by default, and many more are off unless you ask for them. That second group is where the dangerous mistakes hide.

Start with a warning that is on by default. Delete the first line of fee.c, #include <stdio.h>, and build:

gcc -o fee fee.c && ./fee


fee.c: In function ‘main’:
fee.c:7:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
    7 |     printf("Distance: %d km\n", distance_km);
      |     ^~~~~~
fee.c:1:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
  +++ |+#include <stdio.h>
    1 | 
fee.c:7:5: warning: incompatible implicit declaration of built-in function ‘printf’ [-Wbuiltin-declaration-mismatch]
    7 |     printf("Distance: %d km\n", distance_km);
      |     ^~~~~~
fee.c:7:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
Distance: 12 km
Delivery fee: 8.30 EUR


This is the declaration from the first section, missing. Without stdio.h, the compiler reaches printf without having been told it exists. Old C rules let it guess a declaration on the spot, which is what "implicit declaration" means, and it warns you that it guessed. The name in square brackets, [-Wimplicit-function-declaration], is the warning's switch: the option that turns this particular warning on or off. The +++ |+#include <stdio.h> line is a suggested fix, shown as a line to add at the top of the file.

The program still printed the right fee, because the linker found the real printf anyway. That is luck, not correctness: the guessed declaration does not match the real one, and with other functions a wrong guess produces wrong values or crashes. Put #include <stdio.h> back.

Note: From GCC 14 onwards, an implicit function declaration is an error, not a warning. The sandbox runs GCC 13, which still only warns, so you can see both the message and the program that was built anyway.

Now a mistake that is silent by default. Suppose you decide to show the distance with one decimal place and change the first printf to use %.1f:

    printf("Distance: %.1f km\n", distance_km);


gcc -o fee fee.c && ./fee


Distance: 0.0 km
Delivery fee: 8.30 EUR


No message at all, and the distance prints as 0.0. %.1f promises printf a double, but distance_km is an int. On this processor, int and double arguments travel to a function in different places, so printf reads a double from a spot where nothing was put and prints whatever it finds. On your machine it may not be 0.0, which is exactly the problem: the result depends on leftovers, not on your data.

Now build the same file with two extra flags:

gcc -Wall -Wextra -o fee fee.c && ./fee


fee.c: In function ‘main’:
fee.c:8:26: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
    8 |     printf("Distance: %.1f km\n", distance_km);
      |                       ~~~^        ~~~~~~~~~~~
      |                          |        |
      |                          double   int
      |                       %.1d
Distance: 0.0 km
Delivery fee: 8.30 EUR


-Wall turns on a large group of common warnings, and -Wextra adds more on top. Despite its name, -Wall does not enable every warning, which is why the two flags are usually used together. One of the warnings they enable is -Wformat, which checks every printf format string against the types of the arguments. The drawing under the code is the useful part: it labels the placeholder as wanting a double and the argument as being an int.

The suggestion at the bottom, %.1d, is gcc trying to make the placeholder match the argument mechanically. The real fix is to decide what you meant. A distance in whole kilometres is printed with %d, so change the line back to %d. From now on, build with -Wall -Wextra every time. The cost is a few extra characters; the benefit is that a whole class of silent mistakes becomes visible.

Try it: Add the line int stops = 3; right after int distance_km = 12; and build twice, first with gcc -o fee fee.c and then with gcc -Wall -Wextra -o fee fee.c. Predict which build complains. Only the second one does, with warning: unused variable ‘stops’ [-Wunused-variable], because a variable you create and never use is legal C but usually means you forgot something. Remove the line again.


A Function for the Fee, and Why Its Position Matters

The dispatcher wants fees for three stops at once: 12 km, 3 km and 27 km. Copying the formula three times would mean three places to update when the price changes, so the formula belongs in a function: a named block of code that takes values in and gives one value back.

Here is a natural first attempt. main comes first because it is the "story" of the program, and the helper comes after it. Replace the whole of fee.c:

#include <stdio.h>

int main(void) {
    printf("Stop 1: %2d km, fee %5.2f EUR\n", 12, delivery_fee(12));
    printf("Stop 2: %2d km, fee %5.2f EUR\n", 3, delivery_fee(3));
    printf("Stop 3: %2d km, fee %5.2f EUR\n", 27, delivery_fee(27));
    return 0;
}

double delivery_fee(int distance_km) {
    double base_fee = 3.50;
    double per_km = 0.40;
    return base_fee + distance_km * per_km;
}


gcc -o fee fee.c && ./fee


fee.c: In function ‘main’:
fee.c:4:51: warning: implicit declaration of function ‘delivery_fee’ [-Wimplicit-function-declaration]
    4 |     printf("Stop 1: %2d km, fee %5.2f EUR\n", 12, delivery_fee(12));
      |                                                   ^~~~~~~~~~~~
fee.c: At top level:
fee.c:10:8: error: conflicting types for ‘delivery_fee’; have ‘double(int)’
   10 | double delivery_fee(int distance_km) {
      |        ^~~~~~~~~~~~
fee.c:4:51: note: previous implicit declaration of ‘delivery_fee’ with type ‘int()’
    4 |     printf("Stop 1: %2d km, fee %5.2f EUR\n", 12, delivery_fee(12));
      |                                                   ^~~~~~~~~~~~


The function is right there in the file, and still the build fails. The reason is that the compiler reads the file once, from top to bottom. On line 4 it meets delivery_fee(12) without having seen any declaration of delivery_fee, exactly like printf without stdio.h. So it guesses, and the old guessing rule says an unknown function returns int. That is the warning on line 4.

Then, on line 10, it finally reads the real definition, which returns double. Now it has two descriptions of the same function that disagree, int() from the guess and double(int) from the definition, and that is an error: "conflicting types". The note: points back to where the wrong guess was made.

The fix is to tell the compiler about the function before main uses it, with a declaration of its own. A declaration that comes ahead of the definition is called a prototype. Replace fee.c again:

#include <stdio.h>

double delivery_fee(int distance_km);

int main(void) {
    printf("Stop 1: %2d km, fee %5.2f EUR\n", 12, delivery_fee(12));
    printf("Stop 2: %2d km, fee %5.2f EUR\n", 3, delivery_fee(3));
    printf("Stop 3: %2d km, fee %5.2f EUR\n", 27, delivery_fee(27));
    return 0;
}

double delivery_fee(int distance_km) {
    double base_fee = 3.50;
    double per_km = 0.40;
    return base_fee + distance_km * per_km;
}


gcc -Wall -Wextra -o fee fee.c && ./fee


Stop 1: 12 km, fee  8.30 EUR
Stop 2:  3 km, fee  4.70 EUR
Stop 3: 27 km, fee 14.30 EUR


It builds cleanly, even with every warning turned on, and the three fees are right: 3.50 + 3 × 0.40 = 4.70 and 3.50 + 27 × 0.40 = 14.30. Let's go through the new pieces.

  • double delivery_fee(int distance_km); is the prototype. It ends with a semicolon instead of a body. It says: there is a function called delivery_fee, it takes one int, and it returns a double. With this line above main, the compiler can check each call and knows the result is a double. It is exactly the kind of line we found inside stdio.h for printf, which is all a header really is.
  • double delivery_fee(int distance_km) { ... } is the definition, with the actual code. Its first line must match the prototype, or we get "conflicting types" again.
  • Inside it, base_fee and per_km are local variables: they exist only while the function runs, and no other function can see them.
  • return base_fee + distance_km * per_km; computes the fee and hands it back to whoever called the function. In main, delivery_fee(12) is replaced by that returned value, 8.30, which printf then prints.

The format string gained two small details. %2d prints the integer in a field at least two characters wide, padding with a space on the left, so 3 becomes 3 and lines up under 12. %5.2f prints the double with two decimals in a field at least five characters wide, so 8.30 lines up with 14.30. The widths only add padding; they never cut a number off.

Try it: Change the prototype to int delivery_fee(int distance_km);, leave the definition as it is, and build with -Wall -Wextra. Predict the error before you look. You get error: conflicting types for ‘delivery_fee’; have ‘double(int)’ with a note pointing at the prototype, which now says int(int), plus format warnings on every printf, because %5.2f now receives what the compiler believes is an int. Put double back.


Summary

We built a delivery fee calculator for a courier cooperative and used it to learn how C programs are built and how to read what the compiler says about them. We deliberately stayed with one file and hard-coded distances. Reading the distances from the keyboard or from a file, and splitting a program across several files, are the natural next steps and each deserves its own tutorial.

  • A .c file is text for the compiler. gcc -o name file.c turns it into an executable, ./name runs it, and && makes sure you never run a stale program after a failed build.
  • gcc works in three stages: the preprocessor pastes in #include files, the compiler produces an object file, and the linker adds library code such as printf to make a runnable program.
  • The value main returns is the program's exit status; 0 means success, and the shell exposes it as $?.
  • When both operands of / are integers, C does integer division and discards the fraction before any conversion to double, so 2 / 5 is 0. Write 0.40 or make one operand a double.
  • printf placeholders must match their arguments' types: %d for int, %f for double, with .2 for two decimals and a number before it for a minimum width.
  • A gcc message reads as file, line, column, severity, then the complaint. When it says "expected something before X", look at the end of the previous line, and always fix the first error before reading the rest.
  • Compiling cleanly does not mean the program is correct. Build with -Wall -Wextra so that suspicious code, such as a printf format that does not match its argument, produces a warning instead of silently wrong output.
  • Every function must be declared before it is used. Headers like stdio.h provide declarations for library functions, and a prototype above main does the same for your own functions.

Trebuie să fii autentificat pentru a accesa laboratorul cloud.

Autentifică-te