Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculated Constants in C#

Good morning, afternoon or night,

Will either the MSIL or the JIT compiler replace things like 1 << 5 or 1 << 31 in the code with 32 and 2147483648, respectively, or will they wait for method execution to evaluate those constants "just in time" since they involve other methods (operators)?

Thank you very much.

like image 581
Miguel Avatar asked Mar 21 '11 14:03

Miguel


People also ask

How do you calculate constant?

The equation to find the constant of proportionality is written as k = y/x. Here, k is the constant, y is the denominator, and x is the numerator of the ratio.

How is c value calculated?

Calculating C-values The relative molecular mass may be converted to an absolute value by multiplying it by the atomic mass unit (1 u) in picograms. Thus, 615.8771 is multiplied by 1.660539 × 10−12 pg.

What are defined constants in c?

A constant is a name given to the variable whose values can't be altered or changed. A constant is very similar to variables in the C programming language, but it can hold only a single variable during the execution of a program.

What is example of constant in c?

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.


2 Answers

Yes. Look at the compiled IL for a program that just does Console.WriteLine(1 << 5) and you'll see it's the same as that for Console.WriteLine(32) or Console.WriteLine(0x20). The same applies for plenty of other such constants.

like image 29
Jon Hanna Avatar answered Sep 22 '22 12:09

Jon Hanna


Try it.

The following code

    static void Main ( string[] args )
    {
        Console.WriteLine ( 1 << 4 );
    }

Gets compiled to

  IL_0000:  nop
  IL_0001:  ldc.i4.s   16
  IL_0003:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0008:  nop
  IL_0009:  ret

It just loads the constant 16 and passes it to WriteLine.

like image 96
Mongus Pong Avatar answered Sep 22 '22 12:09

Mongus Pong