Thread: How can I enforce type safety?

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    228

    How can I enforce type safety?

    Take this code snippet as an example:

    Code:
    #include<stdio.h>
    
    typedef unsigned foo_t;
    typedef unsigned bar_t;
    
    void func(foo_t foo) {
        printf("foo=%u\n", foo);
    }
    
    int main(int argc, char* argv[]) {
    
        bar_t bar = 0;
        func(bar);
        return 0;
    }
    When I compile this with gcc -Wall it won't even warn me or anything...

    How can I make this raise an error, or at least a warning?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The only thing that typedef does is create aliases. If you create multiple aliases for the same type, then nothing is really wrong and it's your own fault. Plus, even if you made them different integer types you still have to consider integer promotion.

  3. #3
    Registered User
    Join Date
    May 2013
    Posts
    228
    Can you suggest different method by which the above code would at least raise a warning by the compiler?

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by Absurd View Post
    Can you suggest different method by which the above code would at least raise a warning by the compiler?
    Code:
    #include <stdio.h>
     
    typedef struct { unsigned x; } foo_t;
    typedef struct { unsigned x; } bar_t;
     
    void func(foo_t *foo) {
        printf("foo=%u\n", foo->x);
    }
     
    int main(void) {
        bar_t bar = {42};
        func(&bar);
        return 0;
    }

  5. #5
    Registered User
    Join Date
    May 2013
    Posts
    228
    I thought about using structs, but that involves syntax changes that would require changing an existing code.
    Isn't there a way to achieve the same results with primitives?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 09-24-2009, 01:28 AM
  2. C/C++ Type Safety
    By forumuser in forum C Programming
    Replies: 8
    Last Post: 09-23-2009, 12:27 AM
  3. strtok safety
    By Elkvis in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2009, 09:48 AM
  4. Replies: 9
    Last Post: 06-18-2009, 04:58 AM
  5. Enforce a colored-text rule - high contrast
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 05-14-2007, 06:17 AM