Untyped C is bad, mkay?



  • A fragment of code I just encountered:

    	long	response;
    
    	ColorToOS(&style.fg_color, (plat_color_value*)&response);

    All well and good on Windows (where plat_color_value maps to COLORREF, which is four bytes long), and on MacOS (where it maps to RGBColor, again four bytes). But in Cairo (a Linux graphics library), where it maps to a struct containing four doubles, this function call clobbers a large part of the stack.



  • B..but my CS teachers told me C was portable.



  • @Dudehole said:

    B..but my CS teachers told me C was portable.

    C can be quite portable.  But you can make unportable code in any language if you have platform specific libraries which share type or structure names but are wildly different.  Also note that part of C's "portability" is the ability to use #ifdef blocks to select code based on your platform.

    That having been said, C is generally not considered highly portable, and certainly not platform independent, owing to differences like these in many languages.

    One trick to writing portable C is to not use casts except when necessary.  For example, *this* code would be better written as:

    	plat_color_value	response;
    
    ColorToOS(&style.fg_color, &response);
    

    Of course, doing things like that, you have to make more library calls, because you can't make assumptions about your data types.  So, for example, when dealing with output from gettimeofday(2), you need to use timercmp(3), timeradd(3), and timersub(3) to manipulate the output and make comparisons.  This may result in slightly slower code, but it's more portable, and if someone decides to upgrade gettimeofday so that it returns nanosecond resolution, you just need to recomple - rather than feel the need to rip their head off.



  • @tgape said:

    Also note that part of C's "portability" is the ability to use #ifdef blocks to select code based on your platform.

    I would hardly call code forking a feature for portability.



  • @Dudehole said:

    B..but my CS teachers told me C was portable.

     

    If you really want to appreciate how portable C is, you should try running a BASIC program with a few different interpreters.



  • @_moz said:

    If you really want to appreciate how portable C is, you should try running a BASIC program with a few different interpreters.

    Or try several different vendors' FORTRAN compilers!

    (As a side note, nobody who's ever seen someone screaming at VAX C thinks of C as portable...)


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.