Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Declaration  RSS feed

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all... I am declaring an integer like:
int i=012;
When I am printing this value of i, it is printing 10. Why so ?
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because the 0 is meaningless in this case.
it will work if you declare as STRING ...
well actually not so sure
 
lowercase baba
Bartender
Posts: 12624
50
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you declare an integer, and the leading digit is a '0', the compiler considers the value to be an Octal representation of the number. So, in your case, it is reading in 12 base 8.
When you print it out, it converts it to decimal. so you get 1*8 + 2*1 or 10.
 
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can tell octal numbers because they have the preceding 0
so in your case:
int i = 012;
this is how it is represented:
the 0 tells you its octal,
the 1 tells you how many 8's there are, in this case only one,
the 2 tells you how many 1's there are, in this case 2,
so (8*1) + (1*2)= 10
hope this helps.
Davy
 
straws are for suckers. tiny ads are for attractive people.
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!