Search code examples
ctype-safety

Type-safety in C


Is there a way to make C a little more aware of types and assure type-safety?
Consider this:

typedef unsigned cent_t;
typedef unsigned dollar_t;

#define DOLLAR_2_CENT(dollar)       ((cent_t)(100*(dollar)))

void calc(cent_t amount) {
    // expecting 'amount' to semantically represents cents...
}

int main(int argc, char* argv[]) {
    dollar_t amount = 50;
    calc(DOLLAR_2_CENT(amount));  // ok
    calc(amount);                 // raise warning
    return 0;
}

Is there a way to make the above code at-least raise warning by the gcc?
I know I can use C-structs to wrap unsigneds and achieve the desired result, I was just wondering if there was a more elegant way to do it.
Can it be a little more than that?


Solution

  • You need to use a static analysis tool in your build process to achieve this.

    For example, if you run PCLint on your code, it gives this output:

      [Warning 632] Assignment to strong type 'cent_t' in context: arg. no. 1
      [Warning 633] Assignment from a strong type 'dollar_t' in context: arg. no. 1
    

    http://www.gimpel.com/html/strong.htm