Compiler trivia: const, operators and being nice to the compiler

-

This is a ques­tion that came up on our in­ter­nal alias. I thought it might be gen­er­ally in­ter­est­ing to il­lus­trate how the com­piler picks op­er­a­tors.

Here is the orig­i­nal is­sue. This code com­piles fine:

UInt64 vUIn­t641 = UInt64.MaxValue;
const int  vInt2 = 1432765098;
int res = (int)(vUInt641 - vInt2);

But this code gen­er­ates a com­pile er­ror:

UInt64 vUIn­t641 = UInt64.MaxValue;
int  vInt2 = 1432765098;
int res = (int)(vUInt641 - vInt2);

(line 3): er­ror CS0019: Operator -’ can­not be ap­plied to operands of type ulong’ and int’

 The only dif­fer­ence be­tween the two pieces of code is the pres­ence of the const key­word in the first one. Let’s first an­a­lyze the sec­ond case. The rea­son an er­ror is gen­er­ated is that there is no -’ op­er­a­tor de­fined be­tween an ulong and an int. There is also no im­plicit con­ver­sion be­tween int and and ulong or the other way around. The com­piler has to give up and to pro­duce an er­ror.

In the first case the vari­able is marked as const, which means that the com­piler knows its value at com­pile time. It re­al­izes that the value is pos­i­tive and can safely been con­verted to an ulong. The com­piler con­verts it and then in­vokes the -(ulong, ulong) op­er­a­tor.

A bizarre way to think of it is this. As you have been nice to the com­piler by telling him that you are not go­ing to mod­ify this value, the com­piler then is nice to you by mak­ing use of the info to help you out in this case

Remember, al­ways be nice to the com­piler, the more you tell him, the more he tells you

Tags

1 Comment

Comments