Top tips to help the Java programmer code in C


Very common errors noted in preliminary exercises.


1)     TRUE/FALSE/0/1?

        There is no boolean type in C.
        0 : FALSE
        1, or anything other than 0 : TRUE

        e.g. -1, 25, 1, 1389 all evaluate to TRUE

        For further explanation please look here.

2)    == and =

        ==    Boolean evaluation
        =      Variable assignment operator

        Classic cause of problems in C, which I think is caught at compile time in Java.
        NOT NECESSARILY IN C

        e.g.

            int a;
            a=0;     // FALSE
            if (a=1){
                .
                .    some stuff  
                .
            }

        This will result in 'some stuff' being executed regardless of the value of a.
        WHY? Because (a=1) assigns the value 1 to a and the overall expression (a=1) returns 1 in C.
        This is permissible in C, although the compiler should warn you.

        A good habit to get into is always placing the constant on the left of boolean expressions.
        Do you know why?

3)    No function overloading in C

       Two functions cannot have the same name in C.

4)    Variables must be declared at the top of a basic block.

        e.g. The following is OK

        {  int a;
            char b;
              .   
              .
            printf("Hello world\n");
              .
              .
        }    

        However, this is not OK

        {    int a;
                .
                .
                .
              printf("Hello world\n");
                .
                .
              char b;
                .
                .
                .
         }


5. If you MALLOC memory then you must free it (no automated garbage collection in C)
    (Unlikely you will have to worry about this in practical#2)

Some useful links


Learning C from Java
Differences between C and Java

Essentials of C
Summary of basic C language features
Simple C examples

Pointers in C
A tutorial on pointers and arrays in C
A silly pointer example
 
Programming in C UNIX System Calls and Subroutines (Advanced)


Some C Text books in the library


The C programming language / Brian W. Kernighan, Dennis M. Richie

Book on C: programming in C / Al Kelley and Ira Pohl


ANSI C: problem solving and programming / Kenneth A. Barclay



Could not open counter file