Arithmetic conversions and a surprise with 'max'
acehreli at yahoo.com
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.
// An empty line
char 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