Why char * why not bool * can be used in write function in C ++ IO file

In this statement, why use x for char * and not bool * -

out.write( (char*)&(x), sizeof(double) );

      

+3


source to share


2 answers


In this statement, why use x for char * and not bool * ...

It is assumed that you think that bool

, conceptually, one bit is the most basic data type in C ++. This is beside the point. Individual bits are not addressed in C ++. The C ++ memory model is organized around the concept of a byte, which must contain at least eight bits. By definition, a char

(and the related types signed char

and unsigned char

) are one byte long.



These bits are not addressable, since the concept of a boolean data type is not well suited to the memory model. Consecutive gates have either gaps in between (which would be problematic for your proposed click on bool*

), or the boolean can contain much more values ​​than just false

and true

(also problematic; a boolean that contains some value other than false

or true

- behavior undefined).

The C ++ I / O model extends the byte-based memory model to I / O. A C ++ I / O stream contains a sequence of bytes (and sometimes multiple bytes in the case of wide characters), not a sequence of bits. This is why it std::basic_ostream::write

takes a pointer to some type of character (usually char

) and size as arguments.

0


source


The boolean value has two values: true and false.

If every byte in your buffer only has one of two values, it would be an extremely stupid type to fetch arbitrary data.



char

is regarded as a common type "some byte". Therefore, char*

it is the usual type "pointer to some bytes".

+6


source







All Articles