Deep C.

In this thread I will post interesting features and usages (of mostly the C programming language), that might not be known to a novice programmer. I might figure out how to display code nicely, at some other time. 


typedef (declare) a struct name before defining said struct:

typedef struct myStruct myStruct;

struct myStruct {
    myStruct* next
    ...
}; 


You can also typedef (declare) a pointer to a struct without defining the struct to achieve type safety (the pointer cannot point to a struct with a different type), and encapsulation (because it doesn't have access to the definition of said struct).


Constant on the left!

 if(NULL == x){...} is better than if(x == NULL){...} because then you don't get if(x = NULL){...} by mistake



Declare type once:

struct T *p;
p = malloc(sizeof *p);


instead of:

struct T *p;
p = malloc(sizeof (struct T));

Similarly sizeof array = (sizeof (ary) / sizeof (ary[0]))



Single item in list or not in any list?

If element is not in a list, element.next == NULL
If element is only element in list, element.next == element 

But how do we know which list the element is in? Use a pointer?
How can we iterate over a list if the apply function calls a destructor? 



You need to wrap macros in do{…}while(0) or they might behave unexpectedly:

See here

 

It would be nice if I could do the following:

int main (void){
    int i = 0;
    do {
        printf ("A\n");
        i++;
    } while (i < 8){
        printf ("B\n");
    };

}

Comments

Popular posts from this blog

Maths Game.

Diablo II Hell Bovine Figurines

Artificial Sweeteners.