c++ - Where does rand() get its numbers from? -


while working on little project thought generate "random" filenames little bit of code this,

std::cout << "image"+rand()%255 << std::endl; 

the outputs got made no sense me. seem random parts of error messages.

for example piece of code:

int main() {     while(1){         std::cout << "image" + rand() % 255 << std::endl;     }     return 0; } 

produces gibberish like:

> ge > > n > > > > > > ring long > > u > > > > > > & > > n > _ > o >  string position > e > lid string position > > > > > > u > g > invalid string position > > u > ing position > > > & > > > > > ring position > ! > n > > oo long > > > > > > o > position 

and more complex piece of code in qtcreator (with same cout rand endl statement in main loop)

>    atform\mainwindow.cpp:210 >0 >i , null image received >indow.cpp:210 >(qimage) >dimage(qimage) >, error: image not read file! > updateplayerui , null image received >updateplayerui(qimage) >ow.cpp:210 >dimage(qimage) >ot chosen >s not chosen >og, error: image not read file! > not chosen >age not read file! >r: image not read file! >nedataplatform\mainwindow.cpp:210 >error: image not read file! 

what reason this?

the type of "image" const char*, doing pointer arithmetic here

"image" + rand() % 255 

that (potentially) undefined behavior because (likely) accessing outside allocated memory string. intending want

std::cout << "image" << (rand() % 255) << std:endl     

or

std::cout << "image" + std::to_string(rand() % 255) << std:endl 

Comments