Arithmetic conversions and a surprise with 'max'

Ali Çehreli acehreli at
Fri Jun 11 12:00:19 PDT 2010

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.


More information about the Digitalmars-d-learn mailing list