473,722 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ahead of "main"?

mdh
Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
thanks.

Apr 29 '07 #1
25 1908

"mdh" <md**@comcast.n etwrote in message
news:11******** *************@h 2g2000hsg.googl egroups.com...
Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
thanks.
Some early versions of C had local functions, declared within the function
that called them. The idea never caught on, and it is now not possible to
declare functions within main.
Old C also had no prototypes. So if you put functions in reverse order of
hierarchy, the compiler could do additional checking of arguments. Nowadays
we should prototype all functions, so it doesn't matter where main() is
placed, though obviously it should be either the first or the last function
for readbility.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Apr 29 '07 #2
mdh wrote:
Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
Yes. If you use a function before declaring it, the
compiler makes assumptions about the arguments the function
takes and the value it returns. If the assumptions don't
match what the function actually does, you're in trouble.
(The latest compilers try to keep you out of trouble by
making no assumptions; instead, they issue error messages.)

Here's a point to ponder: A function definition -- the
type, name, arguments, and function body enclosed in { } --
not only defines the function, but also declares it (two
two-syllable verbs both beginning with DE, but they are not
the same). It is possible to declare a function without
defining it, by writing all the same things but omitting the
function body and putting a ; where the { }-enclosed stuff
would have been:

double trouble(int fireBurn, int cauldronBubble) ;

This tells the compiler about the arguments trouble() expects
and the type of value it returns, which is enough to allow
the compiler to invoke it properly (and to check for some
errors, like writing only one argument). Anytime after a
declaration line like this, you can call the function and
all will be well.

Still later, at some convenient point in the file, you
can supply the actual definition of the function:

double trouble(int fireBurn, int cauldronBubble)
{
if (fireBurn != 0)
return (double)cauldro nBubble / fireBurn;
else
return 42.0;
}

There are two main reasons (and some less pressing ones)
for wanting to write declaration-only lines. First, as you
move to larger programs you'll find yourself breaking them
up into separately-compiled files: Why should you copy the
entire body of trouble() into twenty different programs, when
you can compile it once in one file and then let all twenty
programs call it? To make this work, you need to write a
declaration-only line for trouble() that the other twenty
programs can use; the usual practice is to put this line in
a .h file the twenty programs can all #include.

A second reason pops up less frequently, but does occur
now and then. What if you have two functions macduff() and
macbeth(), and under some circumstances each of them calls
the other?

double macduff(int x) {
...
if (! i_am_thane)
y = macbeth(x);
...
}

double macbeth(int y) {
...
layOn = macduff(y + 42);
...
}

No matter which definition you place first, the other function's
definition will not have appeared by the time you get to its
call. The compiler will either make a wrong assumption about
the as-yet-undefined function, or will protest and sulk in a
corner. The solution is to write a declaration-only line for
one (or both) of the functions:

double macbeth(int); /* optional: omit arg names */

double macduff(int x) {
...
}

double macbeth(int y) {
...
}

--
Eric Sosman
es*****@acm-dot-org.invalid
Apr 29 '07 #3
mdh
On Apr 29, 1:41 pm, Eric Sosman <esos...@acm-dot-org.invalidwrot e:
mdh wrote:
Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a ... diffference in declaring a function
within "main" or "ahead" of it.
>
Yes. If you use a function before declaring it,.....
Here's a point to ponder: A function definition --..... also declares it (two
two-syllable verbs both beginning with DE, but they are not
the same). It is possible to declare a function without
defining it,......
Thank you....as I do C more and more, I realize that words really
count.


>
There are two main reasons (and some less pressing ones)
for wanting to write declaration-only lines. First, as you
move to larger programs you'll find yourself breaking them
up into separately-compiled files:

>
A second reason pops up less frequently, but does occur
now and then. What if you have two functions macduff() and
macbeth(), and under some circumstances each of them calls
the other?



Thank you Eric.
So, if I understand you correctly, in my case for a small program, the
key seems to be to understand that a declaration needs to occur prior
to the function being called.
Where that declaration actually occurs (prior to main, or within main)
( under these limited circumstances) is of no consequence. However,
once one gets into the "real" world of C, this would be good
programming ( as you noted with seperate .h files), so I may as well
get used to practising good style!!
Apr 29 '07 #4
mdh
On Apr 29, 1:40 pm, "Malcolm McLean" <regniz...@btin ternet.comwrote :
>
Some early versions of C had local functions, declared within the function
that called them. The idea never caught on, and it is now not possible to
declare functions within main.
Old C also had no prototypes. So if you put functions in reverse order of
hierarchy, the compiler could do additional checking of arguments. Nowadays
we should prototype all functions, so it doesn't matter where main() is
placed, though obviously it should be either the first or the last function
for readbility.

tks.

Apr 29 '07 #5
"mdh" <md**@comcast.n etwrote in message
news:11******** *************@h 2g2000hsg.googl egroups.com...
Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
In Standard C, functions cannot be declared "within" main(); these are
called nested functions and are implemented as an extension by some
compilers, but in general you should never use them. Therefore, the debate
is about whether to declare functions before or after main().

As a rule, you should declare all functions before you call them; I won't go
into the reasons why, as Eric did a good job of that. One style is to
define all other functions before main(), which also declares them. The
other is to declare all of your functions in a group near the beginning of
the source, and then you can define them in any order you want. The latter
style is effectively required when you move to multi-file projects, and the
standard practice is to put all of your function declarations in header (.h)
files so that each source file can simply #include the appropriate header
files and then use whatever functions are needed.

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov
--
Posted via a free Usenet account from http://www.teranews.com

Apr 29 '07 #6
mdh wrote:
On Apr 29, 1:41 pm, Eric Sosman <esos...@acm-dot-org.invalidwrot e:
>[...]
Here's a point to ponder: A function definition --..... also declares it (two
two-syllable verbs both beginning with DE, but they are not
the same). It is possible to declare a function without
defining it,......
[...]
So, if I understand you correctly, in my case for a small program, the
key seems to be to understand that a declaration needs to occur prior
to the function being called.
Where that declaration actually occurs (prior to main, or within main)
( under these limited circumstances) is of no consequence. However,
once one gets into the "real" world of C, this would be good
programming ( as you noted with seperate .h files), so I may as well
get used to practising good style!!
I think you are still confusing "declaratio n" and
"definition ." You should declare every function before
trying to call it (modern compilers change "should" to
"must"), but you can define the function wherever you
like. Since a definition is also a declaration (but not
vice-versa), if you define the function before calling
it you don't need a separate declaration. If you define
the function after calling it, or if you define it in a
separately-compiled file, you need a declaration prior
to the first call.

Eventually this will make sense. Trust me.

--
Eric Sosman
es*****@acm-dot-org.invalid
Apr 29 '07 #7
On Sun, 29 Apr 2007 21:40:00 +0100, "Malcolm McLean"
<re*******@btin ternet.comwrote :
>
"mdh" <md**@comcast.n etwrote in message
news:11******* **************@ h2g2000hsg.goog legroups.com...
>Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
thanks.
Some early versions of C had local functions, declared within the function
that called them. The idea never caught on, and it is now not possible to
declare functions within main.
It is certainly possible to declare a function within another.
Defining is prohibited but declaring is allowed. The drawback is that
the declaration has block scope and will not be visible to any other
function in the translation unit.
>Old C also had no prototypes. So if you put functions in reverse order of
Not always possible if function1 and function2 call each other as part
of a recursive algorithm.
>hierarchy, the compiler could do additional checking of arguments. Nowadays
we should prototype all functions, so it doesn't matter where main() is
placed, though obviously it should be either the first or the last function
for readbility.

Remove del for email
Apr 29 '07 #8
Stephen Sprunk wrote, On 29/04/07 22:35:
"mdh" <md**@comcast.n etwrote in message
news:11******** *************@h 2g2000hsg.googl egroups.com...
>Hi all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?

In Standard C, functions cannot be declared "within" main(); these are
called nested functions and are implemented as an extension by some
compilers, but in general you should never use them.
Wrong. They can be *declared* within main or any other function, they
just cannot be *defined* in a function. A declaration says something
exists, a definition says what it is, the difference is important in C.
Therefore, the
debate is about whether to declare functions before or after main().

As a rule, you should declare all functions before you call them; I
won't go into the reasons why, as Eric did a good job of that. One
style is to define all other functions before main(), which also
declares them. The other is to declare all of your functions in a group
near the beginning of the source, and then you can define them in any
order you want. The latter style is effectively required when you move
to multi-file projects, and the standard practice is to put all of your
function declarations in header (.h) files so that each source file can
simply #include the appropriate header files and then use whatever
functions are needed.
Actually, you should not put *all* your function definitions in header
files, since generally there are some which should be local to a given
source file and declared static in that source file. I.e. you should
always limit visibility to the smallest unit that makes sense, since
then you don't have to look as far to see all of the usage.
--
Flash Gordon
Apr 29 '07 #9
On Apr 29, 1:40 pm, "Malcolm McLean" <regniz...@btin ternet.comwrote :
"mdh" <m...@comcast.n etwrote in message

news:11******** *************@h 2g2000hsg.googl egroups.com...H i all,
Going quite methodically through K& R ( as some of you can attest
to!), I have never seen a big diffference in declaring a function
within "main" or "ahead" of it. Now, (p119, K&R II), the discussion
states that "functions "whatever" " should be declared ahead of
main.
Is there a good reason for this?
thanks.

Some early versions of C had local functions, declared within the function
that called them. The idea never caught on, and it is now not possible to
declare functions within main.
Nonsense. There is no problem declaring functions inside main or any
other function. The reasons why you may not want to do so are the
scoping rules, since the declaration would only be visible within the
same block as the declaration. On the other hand, that's perhaps
exactly why you would want to do it on the few occasions where it
makes sense to do so.

Apr 29 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3005
by: Phillip Montgomery | last post by:
Hello all; I'm trying to debug an issue with a java script called, SelectSockets. It appears to be a fairly common one found on the web. I downloaded the SGI Java v1.4.1 installation from SGI's webpage and installed it using SGI's swmgr application. The installation was very straight forward and there were no errors when I installed the package. Then I ran /usr/java2/bin/javac SelectSockets.java to make the SelectSockets.class file.
4
1949
by: Don | last post by:
Is there some way to redirect the "main" frame to another URL from within the "header" frame? Thanks, Don ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =----
9
2190
by: Neelesh | last post by:
Hi all, it is strange that the following code compiles and runs (tested with g++ 3.4.2) #include <iostream> using namespace std; int main(int a, int b, int c, int d, int e) { cout << "hello " << endl;
7
3998
by: David Elliott | last post by:
I have created an application that will dynamically load other DLLs (plugins). The new plugin is a winform with an embedded IE Browser. I am wanting to have the form to run in its own thread. This would allow for other plugins and the main application to be free to do other work. I have written a little TestDriver for the plugin and am having some difficulty. If I don't use threads everything works just fine. If I do use threads, upon...
12
7123
nomad
by: nomad | last post by:
Hi everyone; My Class has ended and I was not able to solve this problem in time, and I would still like to solve it. I got these error code. Exception in thread "main" java.lang.NullPointerException at ticketSales.TicketSales.makeEvent(TicketSales.java:185) at ticketSales.TicketInput.main(TicketInput.java:56) Anyway I have several Class This one is called TransAction
5
3857
by: Summercoolness | last post by:
if you are just a users among the 100s of users on a hosting machines, then if you do a include("/main.php"); it won't include the file but will say Failed opening required '/main.php' (include_path='.:/usr/local/nf/ lib/php') it seems ok to include("../main.php"); except the file will not work if moved from www.abc.com/movies to a new location of www.abc.com/movies/little-mermaid is there a better solution for
2
3959
by: lilyumestar | last post by:
This project is due by Tuesday and I haven't even gotten half of it done. Can anyone please help me with this Exception error? I've been trying to figure it out for several hours Error Message "Main" Java.lang NullPointerException at Project1.sortingByZipCode<Project1.java:80> at Project1.main<Project1.java:31> Here is the Source Code
1
13731
by: jimgym1989 | last post by:
I dont get it..why is the error: Exception in thread "main" java.util.InputMismatchException this is my code /** * @(#)textFileRead.java * * * @author * @version 1.00 2008/10/17 */
3
7654
by: ohadr | last post by:
hi, i get Exception in thread "main" java.lang.NullPointerException when i run my application. the exact error is: "Exception in thread "main" java.lang.NullPointerException at sortmergejoin.MergeJoin.Field(MergeJoin.java:204) at sortmergejoin.MergeJoin.SMJoin(MergeJoin.java:84) at sortmergejoin.MergeJoin.<init>(MergeJoin.java:34) at sortmergejoin.Main.main(Main.java:24) Java Result: 1"
0
8740
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9158
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8059
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6685
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4764
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3208
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2606
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.