Date: Sat, 9 Feb 2013 03:27:25 +0400 From: Solar Designer <solar@...nwall.com> To: john-dev@...ts.openwall.com Subject: Re: C for dummies On Fri, Feb 08, 2013 at 11:52:38PM +0100, magnum wrote: > BTW I always wondered why things like "set_key(char *key, int index)" are not declaring key as const? The non-use of const in JtR is legacy from 1990s when not every C compiler understood const. Of course, I could #define const for compilers not supporting it, or use a #define of another name of my own (and set it to either const or empty string), but I did not bother. > Would that not let the compiler do better optimizations in some cases (apart from detecting bugs)? Or do I over estimate the value of const in that case? I haven't heard of such optimizations being performed by compilers, and I am not sure if our use of const is a contract that we won't write into the array via another pointer (a non-const one). I think not, and this means that there's nothing the compiler can assume here, neither inside the function, nor in the caller. (Of course, we can write via a non-const pointer technically and get away with it, but the question is whether the compiler is free to assume that we don't do it, and whether it'd let our code misbehave in surprising ways if we do it anyway.) This is different from the restrict keyword, which is actually a contract and does allow for optimizations inside the function (that's what it's for), although my understanding is that it's only relevant in functions accepting more than one pointer in their arguments - e.g., in memcpy(). For set_key(), it should not make a difference. restrict is newer than const, so there may still be relevant pre-C99 compilers that don't support it. Besides, if we sign the contract by using restrict and then violate the terms, we may not receive any warning - rather, some builds of the program may misbehave. So restrict makes the code potentially more buggy, unlike const. We may choose to use restrict only in places where we expect it to be helpful for specific reasons. Update: this confirms my understanding that const is not a contract: http://stackoverflow.com/questions/457441/does-restrict-help-in-c-if-a-pointer-is-already-marked-const const on a pointer is merely a tool to have the compiler issue a warning when we write via that pointer. Not only does it not prevent possible writes via other pointers technically, but it's also not a contract that we won't perform such writes in a correctly written program. Alexander
Powered by blists - more mailing lists
Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.