#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, const char *argv[])
{
vector<bool> a;
a.push_back(false);
int t=a[0];
printf("%d %d\n",a[0],t);
return 0;
}
This code give output “5511088 1”. I thought it would be “0 0”.
Anyone know why is it?
The
%dformat specifier is for arguments the size of integers, therefore theprintffunction is expecting two arguments both the size of anint. However, you’re providing it with one argument that isn’t anint, but rather a special object returned byvector<bool>that is convertible tobool.This is basically causing the
printffunction to treat random bytes from the stack as part of the values, while in fact they aren’t.The solution is to cast the first argument to an
int:An even better solution would be to prefer streams over
printfif at all possible, because unlikeprintfthey are type-safe which makes it impossible for this kind of situation to happen:And if you’re looking for a type-safe alternative for
printf-like formatting, consider using the Boost Format library.