[PATCH] clang warning when division of two integer literals loses precision

Tobias Grosser tobias at grosser.es
Sat Aug 24 10:43:26 PDT 2013


On 08/24/2013 03:51 AM, Yaron Keren wrote:
> Hello,
>
> Attached is a patch I made to make clang warn where division of two integer
> literals loses precision. For instance:
>
> double x = 1/2;
>
> Which results in x being 0. This is not the programmer's intention.
> While experienced users will know to code 1.0/2 to force floating division,
> new C/C++ programmers will fall in this trap.
>
> The patch computes the reminder in the division operation and if only if it
> is non-zero, warns and suggests a fix.
>
> This is the first code I write for LLVM so please review it carefully.
> Specifically, I was not sure whether to create another warning group
> in DiagnosticSemaKinds.td or reuse an existing one. Maybe the group should
> be renamed from "DivZero" to "DivProblems".

Wow. This seems really helpful!

As Matt suggested, please resubmit this patch to cfe-commits and add a 
test case.

+//
+  // check for integer constant division by integer constant

Also the comment seems misformatted. Remove the '//', start with an 
uppercase letter and finish the sentence with a point.

Also, here is an interesting test case that you may want to consider.

int foo(float b) {
	float a = 1/2 + b;
}

Suggesting here to transform this into

int foo(float b) {
	float a = 1.0/2 + b;
}

may not be what the user actually wants, as this promotes the whole 
expression to 'double'. Possibly the following is more in line.

int foo(float b) {
	float a = 1.0f/2 + b;
}

Cheers,
Tobias



More information about the llvm-commits mailing list