Slashdot Mirror


Best Practices for Programming in C

An anonymous reader writes "Although the C language has been around for close to 30 years, its appeal has not yet worn off. It continues to attract a large number of people who must develop new skills for writing new applications, or for porting or maintaining existing applications. This article provides a set of guidelines that can help you with your coding."

4 of 123 comments (clear)

  1. use good libraries by nthomas · · Score: 5, Informative
    In addition to the good advice proffered by the article, I should also like to add that using good libraries can make a world of difference.

    For example, for the C program that I'm writing right now, I decided to use GLib -- the base utillity library used by GTK.

    I initially chose it for portability reasons, but soon discovered it had a wealth of cool stuff in it. In addition to providing the standard data structures (trees, hashes, linked lists), it also has a string type ( GString, ) which handles a lot of the string issues that C programmers get bogged down with.

    A lot of the gotchas (buffer overflows, et. al.) mentioned in this article have to do with these string issues, and using GLib's GString data type has enabled me to avoid those.

    There is another library similar to GLib, The Apache Portable Runtime, used in the Apache webserver, and also in Subversion.

    In addition to all this, I'm using XML as the storage format for my program, mostly because libxml takes care of the file parsing issues so I don't have to.

    Bottom line, choose your libraries carefully, they can make a world of difference.

    Thomas

  2. ah, filks... by pb · · Score: 4, Informative

    You can find many more of these here...

    --
    pb Reply or e-mail; don't vaguely moderate.
  3. Re:I agree, and was it wrong about NULL? by orthogonal · · Score: 3, Informative
    I thought you could use NULL to calculate structure offsets, so with something like

    struct _x {
    int a;
    int b;
    }

    it was legal to say &(((struct _x *)NULL)->b)

    to figure out the offset of b within the structure?



    The compiler may be able to do it; you can not, as it involves dereferencing a null pointer, which makes it undefined according to the C Standard.

    You should use the offsetof macro that the Standard supplies, which your compiler may or may not define as (similar to) the construct you're attempting to use.

    You'd use
    offsetof( struct _x, b ) ;
    add apply it to an instance of struct _x as:

    #include <stddef.h>

    void doit( struct _x* ix ) {
    int i = offsetof( struct _x, b ) ;
    int b = *(int*)( ( (char*)ix ) + i ) ; // or
    int* bp = (int*)( ( (char*)ix ) + i ) ;
    }
  4. Re:Looks like the author also knows VB by avalys · · Score: 5, Informative

    The article specifically refers to the snippet you mentioned as pseudocode, not C.

    --
    This space intentionally left blank.