Segment violation (was Re: Why I could not cast string to int?)

bearophile bearophileHUGS at lycos.com
Fri Feb 3 04:53:15 PST 2012


Jonathan M Davis:

> in is pointless on value types. All it does is make the function parameter
> const, which really doesn't do much for you, and in some instances, is really
> annoying.

Having const value types is useful because you can't change them later inside the method. This helps you avoid bugs like:


void foo(int n) {
  // uses n here
  // modifies n here by mistake
  // uses n here again, assuming it's the 'real' n argument
}


When you program you think of arguments as the inputs of your algorithm, so if you mutate them by mistake, this sometimes causes bugs if later you think they are the real inputs of your algorithm still.

Generally in D code all variables that can be const/immutable should be const/immutable, unless this causes problems or is impossible or it causes signficant performance troubles. This avoids some bugs, helps DMD optimize better (I have seen this), and helps the person that reads the code to understand the code better (because he/she/shi is free to focus on just the mutable variables).

It's better to have const function arguments, unless this is not possible, or for not common situations where a mutable input helps you optimize your algorithm better (especially if the profiler has told you so).


> Personally, I see no point in using in unless the parameter is a
> reference type, and even then, it's often a bad idea with reference types,
> because in is really const scope, and the scope is problematic if you want to
> return anything from that variable.

Think of returning a part of a mutable input argument as an optimization, to be used when you know you need the extra speed. Otherwise where performance is not a problem it's often safer to return a const value or to return something new created inside the function/method. This programming style avoids many mistakes (it's useful in Java coding too).
>From what I've seen, in my D code only a small percentage of the program lines need to be optimized and use C-style coding. For most of the lines of code a more functional D style is enough, and safer. The idea is "mutability where needed, and a bit more functional-style everywhere else" :-)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list