Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in declaring a function in Python and C

Tags:

python

c

I am reading and learning now Python and C at the same time. (Don't ask me why, it is a lot of fun! :-)) I use "Learning Python" by Mark Lutz. Here is what he writes about functions in Python:

Unlike in compiled languages such as C, Python functions do not need to be fully defined before the program runs. More generally, defs are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called.

I do not quite get it as in my second book K.N.King says that you CAN declare a function first and create a definition later.

English is not my native language so what I am missing here?

I can make only one guess, that it is somehow related to program runtime. In C the compiler runs through the program and finds the function declaration. Even if it is not defined, compiler goes on and finds function definition later. Function declaration in C helps to avoid problems with return-type of a function (as it is int by default). On the other hand in Python function is not evaluated until it is reached during runtime. And when it is reached, it does not evaluate the body of a function until there is a function call. But this guess does not explain a quote above.

What is then Mr.Lutz is talking about? I am confused a bit...

like image 374
Nikolay Dudaev Avatar asked Jul 13 '26 09:07

Nikolay Dudaev


1 Answers

Python functions are 'executed' when the source code comes to them:

def foo():
    return bar

def bar():
    return 'spam'

Here foo depends on bar, but it doesn't matter that the bar function definition is not executed until after foo has been declared. Only when you then call foo() does the name bar need to exist.

In C however, you cannot do the above without an additional prototype declaration:

char * bar(void);

char * foo(void) {
    return bar();
}

char * bar(void) {
    return "spam";
}

So yes, you can postpone the full declaration of bar but the compiler demands that you still declare the function signature up front.

So Python doesn't care whether or not bar is defined until runtime, C requires functions to be declared at compile time.

like image 165
Martijn Pieters Avatar answered Jul 16 '26 00:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!