CodeQL documentation

Bitwise exclusive-or used like exponentiation

ID: go/mistyped-exponentiation
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - correctness
Query suites:
   - go-security-and-quality.qls

Click to see the query in the CodeQL repository

The caret symbol (^) is sometimes used to represent exponentiation but in Go, as in many C-like languages, it represents the bitwise exclusive-or operation. The expression as 2^32 thus evaluates the number 34, not 232, and it is likely that patterns such as this are mistakes.

Recommendation

To compute 2EXP, 1 << EXP can be used. For constant exponents, 1eEXP can be used to find 10EXP. In other cases, there is math.Pow in the Go standard library which provides this functionality.

Example

The example below prints 34 and not 232 (4294967296).

package main

import "fmt"

func main() {
	fmt.Println(2 ^ 32) // should be 1 << 32
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy