C ++ print pointer does not validate showbase
I noticed an inconsistency in the way the pointers are printed. gcc adds a 0x prefix to the hexadecimal output of the pointer by default, and the Microsoft compiler does not. showbase / noshowbase does not affect any of them.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
void * n = (void *)1;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0x1
// output (VS 2010, 2013): 00000001
n = (void *)10;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0xa
// output (VS 2010, 2013): 0000000A
n = (void *)0;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0
// output (VS 2010, 2013): 00000000
return 0;
}
I am assuming this is implementation-defined behavior, not a bug, but is there a way to stop the compiler from adding 0x? We already add 0x ourselves, but in gcc it appears as 0x0xABCD.
I'm sure I can do something like this ifdef __GNUC___ ....
, but I'm wondering if I'm missing something more obvious. Thanks to
source to share
I suggest you apply to intptr
and treat the input as a normal integer.
Then your I / O manipulators should work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
void * n = (void *)1;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
n = (void *)10;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
n = (void *)0;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
}
// 1
// a
// 0
( live demo )
At first I was a little surprised by your question (more precisely, the behavior of these implementations), but the more I think about it, the more it makes sense. Pointers are not numbers * and there really is no better authority on how to render them than implementation.
* I'm serious! Though, oddly enough, for implementation / historical reasons, the standard calls const void*
"numeric" in this context, using the num_put
locale element for formatted output, eventually deferring to printf
in [facet.num.put.virtuals]
. The standard states that a formatting specifier should be used %p
, but since the result %p
is implementation-defined, you can actually get pretty much anything to do with your current code.
source to share