I'm new to coding so please bear with me.
I'm currently trying to understand the flow and interplay between functions. I understand the basics of how we can call functions, pass arguments between and get return values etc.
However in deconstructing a solution to a practice problem to calculate splitting a bill, asking for user input in form of floats in the main function, these float variables are named
bill_amount
tax_percent
tip_percent
Inside the function to calculate the bill and split it we are using other float variables named
bill
tax
tip
While running the debugger to understand what's going on I can see how these variabels used in the "calculate" function are assigned the values of the variables bill_amount
, tax_amount
and tip_percent
which we get via user input in the main function.
So my question is:
How does C know to pass the values from the variables in our main function to the calculate function? For example the value in tax_percent
getting passed to variable tax
, without specifically instructing the program to do so?
The program works just fine, I've tried googling to understand how this works and have been unsuccessful.
An assignment like x = a;
is an instruction to set x
to the value of a
.
Given a function defined as void foo(int x, int y);
, a function call like foo(a, b);
is an instruction to:
foo
.x
of foo
to the value of a
.y
of foo
to the value of b
.foo
.In a typical C implementation, the way this is done is:
foo(a, b)
is evaluated, the values of a
and b
are stored in places designated for passing arguments to functions, typically certain CPU registers or certain places on the hardware stack.foo
function need the values of x
and y
, they get them from the places the values of the arguments were put.