#Confused on declarations on definitions

1 messages · Page 1 of 1 (latest)

hallow axle
#

here is a function with 2 parameters. Why is this considered better code practice when its less efficient.

You have a declaration above main and a definition below main

why not just do both under?

raven daggerBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

arctic surge
#

You can roughly think about code as being compiled top to bottom, so if you put the declaration below main, the compiler wouldn't have seen it before encountering the call in main and it won't know what to do.

#

;compile ```c
#include <stdio.h>

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
}

int myFunction(int x, int y);
int myFunction(int x, int y) {
return x + y;
}

simple gazelleBOT
#
Compiler Output
<source>: In function 'main':
<source>:4:18: error: implicit declaration of function 'myFunction' [-Wimplicit-function-declaration]
    4 |     int result = myFunction(5, 3);
      |                  ^~~~~~~~~~
Build failed
hallow axle
#

So you can just put declaration anddefinition above main and youd be alright?

arctic surge
#

If you look at my example, you'll see that the declaration actually looks kind of silly.

#

And that's because it is. It's completely pointless.

#

You'd have the same thing if I put both of them above main. The declaration would be completely superfluous.

#

The whole point of the declaration is to tell the compiler that this function exists and give it some basic information about it without defining what it does.

hallow axle
#

Same result with or without

arctic surge
#

Yeah, these two will do the same thing.

hallow axle
#

and even on the bottom

arctic surge
hallow axle
#

how do i use the gcc you used

arctic surge
#

Just type ;compile and then append a code block like this:
```c
code here
```

hallow axle
#

;compile

#include <stdio.h>
int myFunction(int x, int y) {
    return x + y;}


int main() {
    int result = myFunction(5, 3);
    printf("Result is = %d", result);
}

simple gazelleBOT
#
Program Output
Result is = 8
hallow axle
#

Hmm ok seems the other gcc was faulty

#

thanks!

#

!solved