Arithmetic conversions and a surprise with 'max'
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jun 14 05:26:59 PDT 2010
On Fri, 11 Jun 2010 15:00:19 -0400, Ali Çehreli <acehreli at yahoo.com> wrote:
> The following program demonstrates a problem that I just hit. It is a
> known gotcha of arithmetic conversion rules.
>
> The program is trying to center some text around an index of a char
> array. To avoid negative index values, it calls 'max' to limit the
> starting offset at 0.
>
> import std.algorithm;
>
> void main()
> {
> // An empty line
> char[10] line = ' ';
>
> // We want to center some text around the first quarter mark
> int center_of_text = line.length / 4;
> string text = "01234567";
>
> // To be safe, we want to limit the starting index at 0.
> // (No negative index please!)
> int start = max(0, center_of_text - text.length / 2);
>
> assert(start >= 0); // FAILS!
> }
>
> The problem is due to converting the second argument of max to unsigned.
These kinds of things can typically be converted into a different form
that removes the subtraction, or uses it in a safe way:
int start = center_of_text - min(center_of_text, text.length / 2);
-Steve
More information about the Digitalmars-d-learn
mailing list