0

So new to C++ data types and I observed something really weird that I couldn't find answer on the Internet:

std::set<unsigned long> test;
test.insert(7788994347298743234);
test.insert(0113);
std::set<unsigned long>::iterator it;
for(it = test.begin(); it != test.end(); it++) {
  std::cout << *it << std::endl;
}

The output:

75

7788994347298743234

This is a set with "unsigned long int" as element type, which has the range of 0 to 4,294,967,295. Now why does:

  1. A large number like 7788994347298743234 still fits the set just fine and gets printed out? What is C++'s behavior when you try to insert some data that overflows the range of the specified type of the container? It doesn't reject and return false on insertion? Underlying it's using more memory than 32 bit to store that data though?

  2. Any number started as leading zero is invalid? What implicit type conversion has been done to make 0113 become 75?

I ask these because what if my set needs to store elements that could have arbitrary leading zero, say, a result of CRC32 Hash (well just throwing example here, don't know if this actually applicable...)? Thanks!

Superziyi
  • 609
  • 1
  • 9
  • 30
  • 1
    `unsigned long int` is not guaranteed to have that range. A [reference](http://en.cppreference.com/w/cpp/language/integer_literal) for integer literals would not take too long to search for what one starting with a zero means. – chris Mar 30 '15 at 21:16
  • 4
    See http://stackoverflow.com/questions/29325822/c-int-with-preceding-0-changes-entire-value – juanchopanza Mar 30 '15 at 21:16
  • Thanks guys these links help! – Superziyi Mar 30 '15 at 21:27

1 Answers1

0

Okay looks like to be a duplicate then. Feel free to delete it if administrator sees fit. Quick answer to myself after the help with guys in the comments:

  1. The spec says unsigned long int has "at least 32 bits", which means the actual range could go to 64 bits depending on machines and compilers. I was looking at docs like this: https://msdn.microsoft.com/en-us/library/s3f49ktz%28v=vs.80%29.aspx, which is specific to visual studio and was back 2005.

  2. Apparently in C++ leading zero means Octal number. Haven't touched this concept since school, 8 years ago...good links as pointed out by coments: http://en.cppreference.com/w/cpp/language/integer_literal C++ int with preceding 0 changes entire value How does C Handle Integer Literals with Leading Zeros, and What About atoi?

Community
  • 1
  • 1
Superziyi
  • 609
  • 1
  • 9
  • 30