473,765 Members | 2,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Program structure

Hello!

I'm somewhat new to C, and the problem is I'm not sure how to structure my
programs. I keep ending up with massively long main() functions that look
like this:

int main(void)
{
declarations;

if (file_didnt_ope n_or_something) {
return EXIT_FAILURE;
}

if (mem_didnt_allo cate_or_somethi ng) {
close file;
return EXIT_FAILURE;
}

if (another_malloc _failed_or_some thing) {
free mem1;
close file;
return EXIT_FAILURE;
}

if (fread_failed_o r_something) {
free mem2;
free mem1;
close file;
return EXIT_FAILURE;
}

/* etc. */

free(mem2)
free(mem1);
fclose(file);
return 0;
}

I'm pretty sure I'm not using C's control flow constructions intelligently
at all, since this reminds me of x86 assembly language! How would you guys
arrange a program like the one here?

Advice much appreciated
John


Nov 13 '05 #1
4 2271

"John L" <us**@example.n et> wrote in message
news:bk******** **@newsg1.svr.p ol.co.uk...
Hello!

I'm somewhat new to C, and the problem is I'm not sure how to structure my
programs. I keep ending up with massively long main() functions
Refactor. Create small functions that perform a single
task, and call them from main (and/or each other).
that look
like this:

int main(void)
{
declarations;

if (file_didnt_ope n_or_something) {
return EXIT_FAILURE;
}
if(try_to_open_ file(filename) == NULL) /* (you write the
'try_to...' function */
return EXIT_FAILURE;

etc. I'm pretty sure I'm not using C's control flow constructions intelligently
The only control flow you're using (other than calling
library functions) is the 'if' statement and 'return'
statement. They look fine to me. Your 'main()' isnt'
really all that long, and doing it all in main() is
often done for short simple programs.
at all, since this reminds me of x86 assembly language!
Not me.
How would you guys
arrange a program like the one here?

Advice much appreciated
See above.

-Mike
John

Nov 13 '05 #2
John L wrote:

Hello!

I'm somewhat new to C, and the problem is I'm not sure how to structure my
programs. I keep ending up with massively long main() functions that look
like this:

[snip - code]

This is actually pretty reasonable. For example, a program that filters
a file (i.e., processes it such as tab, uncomment, xref (count
word/letter references/frequencies)) is often structured like this:

int
main(int argc, char **argv)
{
/* declare variables */

/* process arguments (changes argc/argv) */

if(argc){
for(i=0; i < argc; i++){
if((fp=fopen(ar gv[i], "r")) == 0){
perror(argv[i]);
exit(1);
}
filter(fp); /* "filter" is often the name of the program
*/
fclose(fp);
}
}else
filter(stdin);
return 0;
}

The idea is that file operations (open/close) are done in the same
scope, and the meat of the program is done by a function which takes an
"open file" as an argument. Processing command line options is
relatively straightforward , so this can be done in main(), assisted by
global option variables. For example, if the usage is

filter [-sdq] [-h n] file...

then you might declare global variables

int sopt = 0;
int dopt = 0;
int qopt = 1;
int hopt = 0;
int harg = 0;

This lets you easily process arguments in main() but use them in the
appropriate lower-level function.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 13 '05 #3
On Fri, 19 Sep 2003 18:45:04 +0100, "John L" <us**@example.n et> wrote:
Hello!

I'm somewhat new to C, and the problem is I'm not sure how to structure my
programs. I keep ending up with massively long main() functions that look
like this:

int main(void)
{
declarations;

if (file_didnt_ope n_or_something) {
return EXIT_FAILURE;
}

if (mem_didnt_allo cate_or_somethi ng) {
close file;
return EXIT_FAILURE;
}

if (another_malloc _failed_or_some thing) {
free mem1;
close file;
return EXIT_FAILURE;
}

if (fread_failed_o r_something) {
free mem2;
free mem1;
close file;
return EXIT_FAILURE;
}

/* etc. */

free(mem2)
free(mem1);
fclose(file);
return 0;
}

I'm pretty sure I'm not using C's control flow constructions intelligently
at all, since this reminds me of x86 assembly language! How would you guys
arrange a program like the one here?


Use a variable for the return code. Also it is safe to call free
with a NULL pointer, so just make sure that all pointer variables
are initialised to NULL.
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int result = EXIT_FAILURE;
char *mem1 = NULL;
char *mem2 = NULL;
FILE *file = NULL;

file = fopen( "test", "r" );
if ( file ) {
mem1 = malloc( 100 );
if ( mem1 ) {
mem2 = malloc( 100 );
if ( mem2 ) {
if ( !fread_failed_o r_something ) {
result = EXIT_SUCCESS;
/* etc. */
}
}
}
}

free( mem2 );
free( mem1 );

if ( file )
fclose( file );

return result;
}

In this particular case I consider it safe to open the file and
allocate memory before any checks for failure. So it would be
simpler to do:

file = fopen( "test", "r" );
mem1 = malloc( 100 );
mem2 = malloc( 100 );

if ( file && mem1 && mem2 ) {
if ( !fread_failed_o r_something ) {
result = EXIT_SUCCESS;
/* etc. */
}
}

Nick.

Nov 13 '05 #4
John L wrote:
Hello!

I'm somewhat new to C, and the problem is I'm not sure how to structure my
programs. I keep ending up with massively long main() functions that look
like this:

int main(void)
{
declarations;

if (file_didnt_ope n_or_something) {
return EXIT_FAILURE;
}

if (mem_didnt_allo cate_or_somethi ng) {
close file;
return EXIT_FAILURE;
}

if (another_malloc _failed_or_some thing) {
free mem1;
close file;
return EXIT_FAILURE;
}

if (fread_failed_o r_something) {
free mem2;
free mem1;
close file;
return EXIT_FAILURE;
}

/* etc. */

free(mem2)
free(mem1);
fclose(file);
return 0;
}

I'm pretty sure I'm not using C's control flow constructions intelligently
at all, since this reminds me of x86 assembly language! How would you guys
arrange a program like the one here?

A little bit like this:

int main(void)
{
int rc = 0;
other declarations;

if((rc = FileOpenedOK()) == 0)
{
if ((rc = AllocationSucce eded()) == 0)
{
if((rc = NextAllocationS ucceeded()) == 0)
{
rc = DoTheThingYouWa nted();
free(SecondLotO fMemory);
}
free(FirstLotOf Memory);
}
fclose(filepoin ter);
}
return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

The trick is to decide at which point it makes sense to split off the guts
of the function into a separate function. I'm not uncomfortable with the
level of nesting shown above, but I wouldn't want it to get too much
deeper.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #5

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

Similar topics

7
3433
by: Randy Yates | last post by:
Hi, I work in an embedded environment in which we often use a mix of C and assembly code. Thus a recurring requirement is to be able to take a C header file with structure definitions as input and create an assembly include file with the structure member offsets defined. The problem is that the structure offsets are a complicated function of other syntactic elements such as other structures (I could have a structure as a member of...
1
1463
by: Robert S | last post by:
Hello group Since I want to modify a large program written in C(40K line) for the academic purposes and the program consists of several modules, it is necessary to have software structure in order to modify the program.Unfortunately the program has no documentation regarding software structure except comments inside code. Anybody knows what is the best tool for extracting structure of the large programs such as one I indicated above.?...
6
3130
by: Ken | last post by:
When running a program in the debugger, what would cause it to crash without any error messages? I get "The program has exited with code 0 (0x0)". The program is a MDI app with threading for several serial ports. It only crashes when data is being received on one or more of the serial ports. Could someone please give me some ideas about what would cause a program to terminate in this way? Thanks....
3
1648
by: Aleramo | last post by:
Can someone understand my errors in this program? in particular the reason cos i receive the worning message. /* Questo programma riguarda il calcolo del mutuo accoppiamento fra patch dell'array. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h>
7
2638
by: Jake Thompson | last post by:
Hello I created a DLL that has a function that is called from my main c program. In my exe I first get a a pointer to the address of the function by using GetProcAddress and on the dll side I make sure that my function is being exported by adding a line to the .def file. This seems to work because when I debug it recognizes the dll and once it hits the function it goes right into the proper location of the dll.
0
1153
by: FishingScout | last post by:
I am re-writing an MS VC++ 6.0 application in Visual Studio 2005 VB.NET. In order for my new application to communicate with some hardware (an RFID reader) I need to communicate with a DLL that was written in MS VC++ 6.0. I have found some excellent discussions that have helped me define the structures to marshal the data between the unmanaged and managed code. My problem is that my application is not working correctly. The result is...
4
1989
by: FishingScout | last post by:
I am re-writing an MS VC++ 6.0 application in Visual Studio 2005 VB.NET. In order for my new application to communicate with some hardware (an RFID reader) I need to communicate with a DLL that was written in MS VC++ 6.0. I have found some excellent discussions that have helped me define the structures to marshal the data between the unmanaged and managed code. My problem is that my application is not working correctly. The result is...
16
4829
by: Martin Joergensen | last post by:
Hi, I wanted to try something which I think is a very good exercise... I read in data from the keyboard and store them in a structure. There's a pointer called "data_pointer" which I use to keep track on the structures... But it's a bit confusing - my program won't compile and I don't know what to do about the warnings/error messages. c:\documents and settings\dell\Desktop\test\main.c(5) : warning
1
1711
by: nickolais909 | last post by:
Hello, I have an old C++ DLL that I am wishing to use in a VB.NET program. Previously I had a VB6 program that would pass a Type to a DLL function. For example, I would pass a variable of this Type in: Public Type ListInfo ' structure to hold information about the list file FileIndex As Integer filename(MAXNAME) As Byte FileNum As Integer
11
2008
by: Ground21 | last post by:
Hello. I'm new // sorry for my english :) I have to write simple program i c++. But I don't know how to code src - program should know it's name (unit1.exe so the name is "unit1" or "unit1.exe" and it's full path (with volume name - c:\programs). Which commends of c++ should I use? (please do not redirect me to 'help', because I must have some "start point" ! :)
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
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
10164
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9959
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
8833
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...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3926
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
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.