size_t to int conversion
Hi
What is the prefered way to convert a size_t variable to an (usigned) int?
Some functions that I use return size_t, for example strlen(). size_t is an unsigned int, but is there a "safer" way to convert it than just
unsigned int temp = strlen( someString );
I get warnings about this when I compile and it annoys me pretty good.
I use VC++ 2003.
thanks
I believe the warning may be caused by setting "Detect 64-bit Portabilities Issues" to "Yes". Try changing it to "No" and they should go away.
Alternativly, just use std::size_t instead of unsigned int, then problem solved!
Alternativly, just use std::size_t instead of unsigned int, then problem solved!
Quote:Original post by desertcube
Alternativly, just use std::size_t instead of unsigned int, then problem solved!
Quoted for emphisis. You can even do using std::size_t and then just type size_t instead of unsigned int.
Quote:Original post by MaulingMonkeyQuote:Original post by desertcube
Alternativly, just use std::size_t instead of unsigned int, then problem solved!
Quoted for emphisis. You can even do using std::size_t and then just type size_t instead of unsigned int.
size_t is actually a typedef in the global namespace, so you don't need the std:: or the using statement.
but is it 64bit-safe to do?:
unsigned int temp = (unsigned int)strlen( someString );
I know a string will hardly require a 64bit variable to hold the length :) but for other cases?
unsigned int temp = (unsigned int)strlen( someString );
I know a string will hardly require a 64bit variable to hold the length :) but for other cases?
Quote:Original post by DeceptI don't see why thet could cause problems, if it's a 64bit machine, then an int with be 64-bits too, won't it?
but is it 64bit-safe to do?:
unsigned int temp = (unsigned int)strlen( someString );
I know a string will hardly require a 64bit variable to hold the length :) but for other cases?
size_t is typically defined as unsigned long. As to 64-bit safe-ness, it would just depend on where and how it is being used. If you "know" that the return value won't exceed 32-bits, then it's safe (but bad form) to cast them to unsigned int. If you don't "know", then it's not safe.
You would probably be better off declaring variables intended to hold values from functions return size_t as size_t.
You would probably be better off declaring variables intended to hold values from functions return size_t as size_t.
Quote:Original post by Evil Steve
I don't see why thet could cause problems, if it's a 64bit machine, then an int with be 64-bits too, won't it?
I'm not sure that's guaranteed, though it is probably true in practice. The standard only requires that an int be at least 16-bits. The intention was for an int to be the natural word size of the processor/platform, but it isn't a requirement.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement