|
|
PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code. Along with the proper indenting it makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/ http://www.cplusplus.com/articles/z13hAqkS/ Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you. You can use the preview button at the bottom to see how it looks. I found the second link to be the most help. |
srand(static_cast<size_t>(time(nullptr)));
.How do I generate random numbers that are different from each other |
|
|
Also this is a better way to write "srand": srand(static_cast<size_t>(time(nullptr))); |
Also this is a better way to write "srand" |
srand((unsigned)time(0));
Handy Andy wrote: |
---|
Also this is a better way to write "srand": srand(static_cast<size_t>(time(nullptr))); |
CppCoreGuidelines wrote: |
---|
C.164: Avoid implicit conversion operators Reason Implicit conversions can be essential (e.g., double to int) but often cause surprises (e.g., String to C-style string). https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c164-avoid-implicit-conversion-operators ES.49: If you must use a cast, use a named cast Reason Readability. Error avoidance. Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors. https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es49-if-you-must-use-a-cast-use-a-named-cast |
Programming Principles and Practice wrote: | ||||
---|---|---|---|---|
5.6.4 Narrowing errors In §3.9.2 we saw a nasty kind of error: when we assign a value that’s “too large to fit” to a variable, it is implicitly truncated. [omissis] we can write a function that tests and throws a runtime_error exception if an assignment or initialization would lead to a changed value. For example:
8.5.7 Argument checking and conversion [omissis] If you really mean to truncate a double value to an int, say so explicitly:
17.8 Messing with types: void* and casts [omissis] The name static_cast is a deliberately ugly name for an ugly (and dangerous) operation. |
char c1 = narrow_cast<char>(1066); // throws |
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value |
|
|
Note The guidelines support library offers a narrow_cast operation for specifying that narrowing is acceptable and a narrow (“narrow if”) that throws an exception if a narrowing would throw away information:
We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
|