Ropes I Know

April 5, 2008

Why C Is a Pile of Shit

(edited for code-readability)

Consider this:

int main()
unsigned int u1 = 1;
unsigned int u2 = 1;
int k;
for (k=-u1; k
Run it. If you, unlike me, expected this program to just print a single empty line, you’ve just acquired “C-guru” status, granted by me.

Now change the variables u1 and u2 to signed int, i.e. remove the ‘unsigned ‘ and you’ll get what I would have expected anyways:

~$ ./a.out

-1 0 1


gcc does not even warn about it, whereas the MS-compiler emits a warning reading something like “sign of an unsigned variable changed, the result remains unsigned”.

What fucks up obscures this issue completely just a twist more, is the fact that if you test k after the for loop for negativity, you’ll just get the right result, i.e. k being negative (-1). Meaning you can assign the negative of an unsigned value to a signed one and it will or may give the expected result, just don’t use it for code that should function.

This is the reason why I force all my co-workers to a) never use unsigned variables, except when in no way avoidable and b) to tell their compilers to treat this warning as an error and force them to think about the unsigned variable once more.

A question remains for me to investigate is “why does this just not work” (in the context of the for-loop, I mean)? I consider this just a purposely set-up trap to catch unsuspecting programmers.

Update (2008/05/31):

As it turns out, this is totally standard-conforming behavior, all types that are not explicitly cast are getting promoted to the type spanning more values. More in the sense of “can represent a higher absolute value”.
And so, when k is assigned -u1, it rightly gets assigned the value -u1, but when it is compared to u1+u2 it is treated as if it had no sign and for that reason will always be bigger than u1+u2.

Since this is completely supported (even defined) by the Standard, it once again evidences what pile of crap the C programming language really is.

I avoid it wherever I can.

To cite someone I can’t remember right now: “I know C(++) better than it deserves!”


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: