Why, in C, does a function need to be declared before it is used?

Asked

Viewed 1,392 times

12

This question was asked on Facebook. Lé is a problem because there is no room for a good answer, there is no way to classify the answers as to their quality properly, much appreciated by the comment, by the opinion, more than a clear and correct answer. So the question remains for future reference on the question.

According to the original question the author came from C# and is having to deal with C now.

That is, you are plotting a wrong path, in my conception, you first understand the concrete, the simple, the easy, there you learn the abstractions that facilitate your life. All learning has always been based on this and has always worked. All attempts to do differently are producing aberrations, so only people who decorate cake recipes and fail to create anything, with criterion, with foundation. This at a time when we are transitioning to a society that will no longer need what is repetitive, will need the creative, so something is very wrong, not for nothing that this is the first generation in history that on average has lower income than their parents at the same age.

So why does C, unlike C#, need to declare the function before using?

Código

#include <stdio.h>

double Somar(double a, double b);

int main() {
    double a, b;
    printf ("Digite a: ");
    scanf("%d", &a);
    printf ("Digite bi ");
    scanf("%d", &b);
    printf("O resultado eh %d", Somar(a, b));
}

double Somar(double a, double b) {
    return a+b;
}

1 answer

14


Much of what is here has even been answered in the original post on FB, but inconsistently and with wrong options. Here is an attempt to consolidate knowledge of how it really works.

The direct answer to the question is that the compiler C is a single step (and when we talk about a step we are talking about the Parsing, not of the other compilation phases). It does the Parsing as you read the code and decide what to do. This simplifies the compiler, makes it faster and even the language specification is simpler. If you want to understand more about How is a compiler made?.

C# has two steps, first it reads all the code and interprets the data structure, thus assembling the classes and understanding all their members, and even if something cannot be determined at that moment it marks to complete later. Done this it can take care of the algorithms that is analyzed in a second step.

Clearly this is more complicated and slower. Nothing critical for a language created in this century, but it was a problem for a language created almost 50 years ago.

Why don’t you change that now? Because all language was thought to be like this, all code was written based on this premise, this change would bring few benefits and likely harm to the legacy. C is so successful out of respect for the legacy, whether it’s a plus or minus.

And it’s still part of the philosophy of language to let you understand everything that’s going on, not to hide too much. That’s why people should learn C first and then learn other languages, only then produce real developers, which is becoming proportionally rare to find, so today you find "senior developers" who don’t understand what they’re doing, the so-called functional illiterates. They produce complex applications that work, but only because they’re reproducing what they’ve seen ready elsewhere.

Really C# gives a huge ease, but has nothing to do with what is expected of C. The language created by Dennis Ritchie aims to be a portable Assembly and not a language Nterprise.

Some say it is so to be faster, but this does not make the code faster, at most the compilation is slightly faster. Alias is a myth that C is a faster language. It just makes it more obvious and simple for the programmer to produce faster code. It won’t be faster just because it’s C. A lot of people produce extremely slow codes in C. And in cruel detail, they’re only so slow because it’s written in C. One doesn’t understand certain peculiarities and makes more mistakes than in other languages, for example using strlen().

But there is an error in the premise of the question and this is something that I see almost everyone learning wrong, often because they use bad or old material, when it is not the teacher’s fault. C has evolved a lot, C today values readability more, and understands that some things no longer make sense. This code can be better written:

#include <stdio.h>

double Somar(double a, double b) {
    return a + b;
}

int main() {
    double a, b;
    printf ("Digite a: ");
    scanf("%d", &a);
    printf ("Digite bi ");
    scanf("%d", &b);
    printf("O resultado eh %d", Somar(a, b));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The function needs to be declared before, but can together with the declaration and become one thing.

Some people there said on Facebook that the correct thing is to put the statement, called a prototype, in a header file. This is even correct depending on the context. It does not seem the case, this function should be used only there, so it makes no sense to declare in header. The header file only makes sense for function reuse. Even in larger codes this function should probably be declared as static not to be seen elsewhere.

Another mistake is thinking that only the statement should be in the header. In many cases yes, but there are cases that the implementation should already be in it, especially these simpler and that can be linearized. Often one doesn’t understand why one needs to use the include and link along (See more).

The separate statement of the definition only makes sense when it will use a header (and this allows some tricks that C# does not allow, but goes far beyond the scope of the question talk about it), yet only in some cases makes sense to separate; and it also makes sense when there is circular reference, so you need to first declare it to be used in another function, and then you can define the function using a previously defined function. This is not the case with the question. It is important to understand the difference between declaration and definition, according to link above.

Contrary to what many imagine in C# can also do this, and in some cases need to declare the function separate from the definition.

So some say it’s not mandatory, and they’re right in the sense that I explained. It is mandatory to declare, but not always need to declare separate from the definition. If you can define before the use is already valid.

The declaration is not only useful, it is not only facilitating, it is mandatory to decide whether the code is valid. A compiled language intended to give a minimum of robustness accurately indicates whether the function can be called correctly.

Some said to declare within the function main() and it’s not wrong, but I don’t like it. I think declaration of something higher level should always be at the higher level. This if it makes sense to declare before setting, which is rare. For me it is asymmetrical when using with header. In almost all situations where it does not use header just set before, is the most correct. If it has no circularity it has zero benefit declare before setting. Even the idea of wanting the main() before no glue, this leaves nothing more readable.

Nothing has to do with low level (it was said there), it is possible to be low level and not have it and be high level and have this need.

Secondarily they talked about the return of the function. And yes, the function main() as an entry point should always return an integer to the operating system. But it is not required to write this return code, the compiler usually puts it to you if it is the default. And it is possible to return void (some compilers are set by default not to accept this, but may change).

They talked about #region. This mechanism is perhaps the most disputed of the language, and in the background is an embellished comment. The IDE makes useful use of it, so it can simulate in C, it just shouldn’t be used, when it is needed it has other code problems.

Have some good remarks there, as on Hoisting.

Some people have observed that the use of %d is wrong, I believe the person must have associated the letter with the type, but no, the correct would be %lf. The most correct even in real code is to do something more sophisticated, but for exercise is good.

But the point is not to work, it is to do it right, and preferably idiomatically in C, which is different from C# and other languages, even C++ which is contrary to what many believe is a completely different language.

Fiat 147 detonado andando pelas ruas

There are many wrong comments there (even with Likes), but I’m not going to speak one by one. And there are crazy things too, I don’t know who must have arrived from the carnival and posted there...

Finally, first you have to learn programming, learn computing (assuming that one already knows mathematics, communication and expression, science, everything important for programming well), then you have to learn languages that is the easy and almost irrelevant part (one of the world’s largest computers did not have a computer), yet it needs to learn in depth, to really understand what it is doing. I try to program primarily in C# today, but only because I have a choice, not because it’s the only thing I know.

Well, we have to be careful with the information we receive, especially from random people on the Internet, especially on sites with no commitment to quality, where informality is the standard. There is a lot of information on the Internet, but not all is good. Always contest. Go deeper. Follow links, look for opposite positions and worry if not find. Read everything you can. Facebook is probably the worst place to ask about programming for several reasons. And of course, the person always has the right of choice to be an amateur, and has the right to even have made this choice to complain about the labour market not valuing it. And for those who do not know Sopt, send criticism, we can always improve the answers, or we can have better answers.

If you want to know more or been floating on something, search here on the site, has enough material already rated by experts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.