Selcon
asked on
size() of vector gives type conversion warnings
Hi,
I recently inherited this library (the source code) which uses STL vectors. I'm running it in VC++ v7.0.9466 and .NET framework 1.0.3705, and everytime i compile, i get a whole bunch of warning messages about "conversion from 'size_t' to 'blah', possible loss of data."
For example, the code below will produce 2 such warnings.
#include <vector>
void main() {
std::vector<unsigned int> temp(5);
int foo = temp.size();
unsigned bar = temp.size();
}
I understand that the size() method returns a type of size_t, which explains the warning messages. But is there a way to make VC++ detect that for example it is actually an unsigned and not produce unnecessary warnings? Even though the warnings are harmless, I just don't like getting tons of warning messages everytime I compile.
Thanks.
I recently inherited this library (the source code) which uses STL vectors. I'm running it in VC++ v7.0.9466 and .NET framework 1.0.3705, and everytime i compile, i get a whole bunch of warning messages about "conversion from 'size_t' to 'blah', possible loss of data."
For example, the code below will produce 2 such warnings.
#include <vector>
void main() {
std::vector<unsigned int> temp(5);
int foo = temp.size();
unsigned bar = temp.size();
}
I understand that the size() method returns a type of size_t, which explains the warning messages. But is there a way to make VC++ detect that for example it is actually an unsigned and not produce unnecessary warnings? Even though the warnings are harmless, I just don't like getting tons of warning messages everytime I compile.
Thanks.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
is that the best way to deal with these warnings?
so in all projects that use STL vector, there will be static_cast<> all over the place, especially in loops across elements in a vector, etc.? or there will be size_t all over the place i suppose.
so in all projects that use STL vector, there will be static_cast<> all over the place, especially in loops across elements in a vector, etc.? or there will be size_t all over the place i suppose.
Yes, without disabling the warning, those are your choices.
I try to use size_t where I can and then use static_cast to handle cases where the target value is already a smaller integer type.
I try to use size_t where I can and then use static_cast to handle cases where the target value is already a smaller integer type.
unsigned int foo = temp.size();
But, why not to use this instead?
size_t foo = temp.size();
Anyway, to avoid an specific warning message you can use a pragma directive in the top of your files:
#pragma warning( disable : 9999 )
where 9999 is a warning code.