Thanks. But this variable holds a value that comes from the standard
function "ftell". It'd be something like,
fseek (fp , 0 , SEEK_END);
size = ftell (fp); /* ftell gives me long int. */
rewind (fp);
So I think I won't be able to make it a size_t. Not sure how to go
about this. Any help?
Well, you're in the land of platform specific behavior. In my
opinion, the best way to handle this is to make an assumption about
the conversion between size_t and long int and stick to it. If you're
assumption isn't held, you fail the compiler so that if a person
compiles your code on a different platform with different assumptions,
the compiler flags the person down before getting on the bus to the
city of Undefined Behavior.
If you decide to go down this path, this is where I'd consider using a
static assertion mechanism. The C construct is found in the archives,
and C++ has a static assertion as well. The one that I use is the
following (not sure who the first one was in the archive to come up
with it though):
\code
#define STATIC_ASSERT(name, expr) extern char (name)[(expr) ? 1 : -1]
\endcode
If 'expr' evaluates to false, you attempt to reference an array with a
negative sign, causing a compiler error. In the syntax of the
compiler error message, you find the 'name' which gives a hint at the
failure point. You can use this in this kind of context.
\code
#include <stdlib.h>
#include <limits.h>
STATIC_ASSERT( CHAR_BIT_is_8_bits, CHAR_BIT == 8 );
STATIC_ASSERT( sizeof_int_at_least_32_bits, sizeof(int) >= 4 );
int main(void)
{
... your stuff here ...
return EXIT_SUCCESS;
}
\endcode
If I require CHAR_BIT to be 32-bits for code specific to a particular
dsp, I can use the following
\code
#include <stdlib.h>
#include <limits.h>
STATIC_ASSERT( CHAR_BIT_is_32_bits, CHAR_BIT == 32 );
int main(void)
{
return EXIT_SUCCESS;
}
\endcode
And when I compile this on my PC, I get an error message that reads
\error
STATIC_ASSERT_example.c:4: error: size of array 'CHAR_BIT_is_32_bits'
is negative
\enderror
So with a static assertion, you can define the sandbox where your code
will do what you intend, and anyone outside the sandbox will be forced
to deal with the compiler error. I'm not completely positive what
'expr' to use in the static assert, but my first guess would be.
STATIC_ASSERT( size_t_compatible_with_ftell, sizeof( size_t ) >=
size_t( long int ) );
Just an idea to throw around.
Best regards,
John D.