1

In the functions short for week 2, we see the basic adder and multiple functions. The code for this function looks like:

int mult_two_reals(int a, int b);


int main(void)
{
    printf("Give me a real number: ");
    int x = GetInt(); 

    printf("Give me a real number: ");
    int y = GetInt(); 
    int z = mult_two_reals(x, y);

    printf("The product of %i and %i is %i!\n", x, y, z);

}

int mult_two_reals(int a, int b)
{
    int product = a * b;
    return product;
} 

I was wondering why we define the mult_two_reals function only after the entire main block? From what I see, the computer reads the call to the function, but then only finds the definition of the function at the end of the code. Is this the most efficient way?

1 Answer 1

1

Well in standard C, defining a function within another function is not actually allowed (though some compilers support it anyway). Regarding efficiency: while it is true that there is a small amount of cost to calling a function, it's small, outside the scope of CS50, and doesn't really have anything to do with its location in the file (e.g., defining the function before main wouldn't make a difference).

It's important to remember there are two phases during which the computer "reads" the code. The first is during compilation, when it translates C into machine code that the processor can understand, and the second is when the processor actually interprets those instructions when the program is run. After the program is compiled, there's no searching for the definition of the function. This is a fairly large oversimplification, but every function has a memory address that is asociated with it during compilation, and essentially the processor just begins reading instructions starting from that that address.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .