3

Having perused the MSDN documentation for both the ^ (hat) operator and the Math.Pow() function, I see no explicit difference. Is there one?

There obviously is the difference that one is a function while the other is considered an operator, e.g. this will not work:

Public Const x As Double = 3
Public Const y As Double = Math.Pow(2, x) ' Fails because of const-ness

But this will:

Public Const x As Double = 3
Public Const y As Double = 2^x

But is there a difference in how they produce the end result? Does Math.Pow() do more safety checking for example? Or is one just some kind of alias for the other?

Toby
  • 9,696
  • 16
  • 68
  • 132

1 Answers1

5

One way to find out is to inspect the IL. For:

Dim x As Double = 3
Dim y As Double = Math.Pow(2, x)

The IL is:

IL_0000:  nop         
IL_0001:  ldc.r8      00 00 00 00 00 00 08 40 
IL_000A:  stloc.0     // x
IL_000B:  ldc.r8      00 00 00 00 00 00 00 40 
IL_0014:  ldloc.0     // x
IL_0015:  call        System.Math.Pow
IL_001A:  stloc.1     // y

And for:

Dim x As Double = 3
Dim y As Double = 2 ^ x

The IL also is:

IL_0000:  nop         
IL_0001:  ldc.r8      00 00 00 00 00 00 08 40 
IL_000A:  stloc.0     // x
IL_000B:  ldc.r8      00 00 00 00 00 00 00 40 
IL_0014:  ldloc.0     // x
IL_0015:  call        System.Math.Pow
IL_001A:  stloc.1     // y

IE the compiler has turned the ^ into a call to Math.Pow - they're identical at runtime.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • 2
    Not sure in VS - personally I just chuck snippets like this into [LINQPad](https://www.linqpad.net/), like [this](https://i.stack.imgur.com/ZRO4F.png). – James Thorpe May 05 '17 at 12:33
  • Cool, FYI I just found https://dotnetfiddle.net/ that does similar but online, also shows IL :-) – Toby May 05 '17 at 12:39