Opened 16 years ago

Closed 16 years ago

#892 closed Bugs (Invalid)

boost::counting_iterator

Reported by: nobody Owned by: david_abrahams
Milestone: Component: iterator
Version: None Severity:
Keywords: Cc:

Description

The following example code

boost::counting_iterator<int> pi1(3);
boost::counting_iterator<int> pi2(7);
printf("diff %d, %d\n", pi2 - pi1, 5);

should print
  diff 4, 5
but instead wrongly prints
  diff 4, 0

Tested with gcc.

Change History (3)

comment:1 by ljj116, 16 years ago

Logged In: YES 
user_id=1766784
Originator: NO

It's because the subtraction results in a 64-bit number.  %d is only expecting 32 bits, so the first 32 bits from the stack goes to the first %d and the second 32 bits goes to the second %d.  The third 32-bits (5) is never accessed by the printf function.

If you really want to do that, use:
printf("diff %d, %d\n", (int)(pi2 - pi1), 5);

The same thing happens if you use this code on a machine where long long is 64 bits:
long long my64bitnum = 4;
printf("diff %d, %d\n", my64bitnum, 5);

comment:2 by ljj116, 16 years ago

Logged In: YES 
user_id=1766784
Originator: NO

or 
printf("diff %lld, %d\n", pi2 - pi1, 5); 

if you want all 64 bits.

comment:3 by david_abrahams, 16 years ago

Status: assignedclosed
Logged In: YES 
user_id=52572
Originator: NO

Closing since this is clearly not a bug in counting_iterator.  Use C++ iostreams or Boost.Format if you want typesafe I/O.

Note: See TracTickets for help on using tickets.