views:

325

answers:

4

I get a warning in MSVC++ when I try to read an integer from a file and make a bool variable equal it.

accessLV[i] = FileRead(file1, i + 1);

(accessLV is an array of bools, FileRead is a function I made to decrease the syntax involved in reading from a file, i is because the statement is within a for loop)

I've tried using a static_cast:

accessLV[i] = static_cast<bool>(FileRead(file1, i + 1));

But I still get the warning. I've tried doing this (I'm not sure the exact term):

accessLV[i] = (bool)FileRead(file1, i + 1));

And the warning is still there. Is there anyway to get rid of the warning without making accessLV an array of ints?

NB: this is the syntax of FileRead, if it helps:

int FileRead(std::fstream& file, int pos)
{
    int data;
    file.seekg(file.beg + pos * sizeof(int));
    file.read(reinterpret_cast<char*>(&data), sizeof(data));
    return data;
}
+8  A: 

How about

accessLV[i] = FileRead(file1, i + 1) != 0;
Dave
An extra set of ( ) wouldn't go astray there just to show where the precedence is!
Richard Corden
+3  A: 

What you want to do is basically

accessLV[i] = (FileRead(file1, i + 1) != 0)

leiz
+2  A: 
accessLV[i] = FileRead(file1, i + 1) != 0;

Above, you were casting from int to bool: if you use this, the result of the comparison is put in accessLV[i], so not type warnings occur.

Nathaniel Flath
+2  A: 

As other posters have suggested, !=0 is what you need. I prefer a wrapper like this because I find it more readable:

// myutil.hpp
template< typename T >
inline bool bool_cast( const T & t ) { return t != 0; }

Which you would use in this case like this:

// yourcode.cpp
accessLV[ i ] = bool_cast( FileRead( file1, i + 1 ) );

This related question has additional discussion you might find useful.

jwfearn