warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data — C++

前端 未结 4 1905
栀梦
栀梦 2020-12-13 19:36

I made a simple program that allows the user to pick a number of dice then guess the outcome... I posted this code before but with the wrong question so it was deleted... no

相关标签:
4条回答
  • 2020-12-13 19:38

    This line involves an implicit cast from time_t which time returns to unsigned int which srand takes:

    srand ( time(NULL) );
    

    You can make it an explicit cast instead:

    srand ( static_cast<unsigned int>(time(NULL)) );
    
    0 讨论(0)
  • 2020-12-13 19:54

    time() returns a time_t, which can be 32 or 64 bits. srand() takes an unsigned int, which is 32 bits. To be fair, you probably won't care since it's only being used as a seed for randomization.

    0 讨论(0)
  • 2020-12-13 19:55

    That's because on your system, time_t is a larger integer type than unsigned int.

    • time() returns a time_t which is probably a 64-bit integer.
    • srand() wants an unsigned int which is probably a 32-bit integer.

    Hence you get the warning. You can silence it with a cast:

    srand ( (unsigned int)time(NULL) );
    

    In this case, the downcast (and potential data loss) doesn't matter since you're only using it to seed the RNG.

    0 讨论(0)
  • 2020-12-13 19:59

    This line involves an implicit cast from time_t which time returns to unsigned int which srand takes:

    srand ( time(NULL) );
    

    You can make it an explicit cast instead:

    srand ( static_cast<unsigned int>(time(NULL)) );
    
    0 讨论(0)
提交回复
热议问题