Parsing numbers in C based languages

In some C based languages such as C++, Java or Javascript any leading zeros at the start of a number will cause that number to be treated as octal (base 8).

This peculiar issue can occur in templating or anything else where a text input will be treated as a number.

This can occur in Javascript

var test1 = 10;
var test2 = 010;

alert(test1); // outputs '10'
alert(test2); // outputs '8'

Java

public static void main (String[] args)
{
  int test1 = 10;
  int test2 = 010;

  System.out.println("test1: " + test1);
  System.out.println("test2: " + test2);
  
  /*
  test1: 10
  test2: 8
  */
}

C++

int main() {

int test1 = 10;
int test2 = 010;

printf("test1: %i\ntest2: %i", test1, test2);

return 0;
    
    /*
    test1: 10
    test2: 8
    */
}

Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.