C++ IOS Library - Iword



It is used to get integer element of extensible array and returns a reference to the object of type long which corresponds to index idx in the internal extensible array.

If idx is an index to a new element and the internal extensible array is not long enough (or is not yet allocated), the function extends it (or allocates it) with as many zero-initialized elements as necessary.

The reference returned is guaranteed to be valid at least until another operation is performed on the stream object, including another call to iword. Once another operation is performed, the reference may become invalid, although a subsequent call to this same function with the same idx argument returns a reference to the same value within the internal extensible array.

The internal extensible array is a general-purpose array of objects of type long (if accessed with member iword) or void* (if accessed with member pword). Libraries may implement this array in diverse ways: iword and pword may or may not share a unique array, and they may not even be arrays, but some other data structure.


Following is the declaration for ios_base::iword function.

long& iword (int idx);


idx − An index value for an element of the internal extensible array. Some implementations expect idx to be a value previously returned by member xalloc.

Return Value

A reference to the element in the internal extensible array whose index is idx. This value is returned as a reference to an object of type long.or else a valid long& initialized to 0L is returned, and (if the stream object inherits from basic_ios) the badbit state flag is set.


Basic guarantee − if an exception is thrown, the stream is in a valid state.

Data races

May modify the stream object. The returned value may also be used to modify it. Concurrent access to the same stream object may cause data races.


In below example explains about ios_base::iword function.

#include <iostream>     

std::ostream& Counter (std::ostream& os) {
   const static int index = os.xalloc();
   return os << ++os.iword(index);

int main() {
   std::cout << Counter << ": first line\n";
   std::cout << Counter << ": second line\n";
   std::cout << Counter << ": third line\n";
   std::cerr << Counter << ": error line\n";
   return 0;

Let us compile and run the above program, this will produce the following result −

1: first line
2: second line
3: third line
1: error line