LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Blogs > hazel
User Name
Password

Notices


Rate this Entry

Some tips on programming in C

Posted 07-18-2019 at 01:11 PM by hazel
Updated 07-21-2019 at 11:38 AM by hazel

Many people, after using Linux for a while, get the programming bug. I doubt if that often happens to Windows users, but Linux offers such convenient tools for writing programs that it tempts you to put one toe into the water.

Here are one or two tips that you might want to follow to make programming less stressful and confusing. I have chosen C as the language because it's one I know something about. Most of what I want to say applies just as much to C++. Some of it probably applies to other languages like Python of which I know nothing!

First, don't just start writing C code. Rough it out first using a pseudo-code. For example:
Code:
/* Program to compare two files */
{
    Check number of arguments 
    If (arguments != 2)
    {
    print usage statement
    exit (2)
    }
    Open file arg[1]
    On error
    {
        print "Invalid filename"
        exit (2)
    }
    Open comparison_file
    On error
    {
        print "Oops! Comparison file not found"
        exit (2)
    }
    Check arg[2]
    If not integer
    {
        Print "Invalid line number"
        exit(2)
    }
    Read line arg[2] of file arg[1]
    Read line arg[2] of comparison_file
    If the same
    {
        print "Lines match"
        exit (0)
    }
    else
    {
        print "File mismatch on line arg[2]
        exit(1)
     }
}
A quick look at this shows that the files haven't been closed again. So the last few lines should be:
Code:
  If the same
    {
        print "Lines match"
        exit_code=0
    }
    else
    {
        print "File mismatch on line arg[2]"
        exit_code=1
    }
    close arg[1]
    close comparison_file
    exit (exit_code)
    }
}
Now you can begin to translate your pseudocode into valid C. Here are some tips that will make your code easier to understand two weeks after writing it:
  • Add plenty of explanatory comments.
  • Use informative names for variables and functions.You can use snake_case or CamelCase to make them easy to read.
  • Write all your code in a syntax-checking editor like vim or gedit. This will avoid obvious errors like unterminated comments or strings.
  • Place braces that are supposed to match directly under each other. This will make mismatches easy to spot. Just place your cursor on an opening brace and check that the closing brace which lights up is the correct one.
  • Use indentation to show the logic of the program. All lines other than comments and function headers should be indented by one tab. This will allow you easily to insert debugging statements later; just start them in column 1 and they'll stick out like sore thumbs, making them easy to remove when they've done their job. Use further indentation to show compound instructions (loops, conditional blocks).
  • Follow standard conventions. For example your main() function should return int (for the error code) and have the arguments argc and argv[]. You may not have any use for these initially but having them in place often proves useful later.
  • Remember to #include appropriate header files for any library functions that you use. Otherwise gcc will complain that you have implicitly redefined them. The man pages for functions always list the headers that define them as well as exhaustively describing the argument syntax. Your own functions need to be declared in a header whenever it is not a simple job to define them before you call them.

The first time you compile your code, you will probably get a storm of errors. They will roll up off the top of the screen so fast that you will only see the last few of them. It is very tempting to check these first.Do not fall for this temptation. When gcc detects an error which makes it impossible to compile that statement, it simply drops it, and that will cause consequent errors further down. You can study those lines of code until the cows come home and you will never be able to see what is wrong with them because there is nothing wrong. They just happen to depend on an earlier line that failed to compile.

Scroll back to the beginning of the output and find the first reported error. Study it and correct it. Then recompile and you will find that many of the later errors simply disappear.

Sometimes gcc gives warnings rather than errors. A warning means that the line can be compiled but the result might not be what you want. In fact warnings often indicate errors in your program logic that will cause run-time bugs so you should always take them seriously. Two common examples are:
  • using "=" (assignment) instead of "==" (comparison) in a condition. An assignment is always true (except assignments of zero which are always false) so that comparison will never work.
  • putting a value of one type into a variable of another without explicitly casting it to the new type. A common cause of that is accidentally using the wrong variable name! The types don't match because that value and that variable were never meant to go together.

If your program compiles successfully, you are now ready for the test-debug-edit-recompile cycle. This will take a long time and much hair-pulling! At first the bugs are obvious. The program just doesn't work. It doesn't do what it is supposed to do. I find that the best way to approach this is to put in a lot of temporary printf() statements beginning in column 1. Print out the values of variables and let functions tell you when they run. I remember I once had an incrementing pointer that failed to increment. Printing out the addresses as the loop ran showed me that they were all the same and then it was easy to find out why.

When you finally have a program that works when you do exactly what you are supposed to do, try doing something different and see if it still works. You'll have to put in a whole new lot of error checks! Then get a friend to beta-test it and they'll do things you never even dreamed of because those things are obviously stupid. Obviously stupid to you, that is, because you know what you should be doing. So bullet-proof your code!

Follow these rules and you're more likely to get a favourable response from the forum when you post your problem.
Posted in Programming
Views 199 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 11:42 PM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration