N
Nikita The Spider
Hi all,
I'm scraping many years of rust & barnacles off of my C skills, and
I'm stuck at my first knotty and interesting problem.
I'm writing some code that needs to be cross platform and it uses
several typdef-ed numeric types. For instance, a key_t could be typdef-
ed as an int, ulong, etc. I need to be able to figure out what the
maximum value is that can be stuffed into the key_t and other types.
I've read some of the other threads on this problem[1] and there seems
to be no straightforward solution. Can someone help me understand why
the code below not work? (Please ignore the dodgy assumption in the
printf() that long long is supported.)
#include <stdio.h>
typedef long foo_t; // This represents my unknown type
int main (int argc, char const *argv[])
{
foo_t test_value;
foo_t max = 127;
int found = 0;
while (!found) {
test_value = (max * 2) + 1;
if ( (test_value <= max) || (test_value != ((max * 2) + 1)))
// overflow!
found = 1;
else
max = test_value;
}
printf("max: %llu\n", (unsigned long long)max);
return 0;
}
[1] Some previous threads on the subject:
http://groups.google.com/group/comp.lang.c/browse_thread/thread/d6f967e56fa87617
http://groups.google.com/group/comp.lang.c/browse_thread/thread/84628b61f288bcb2
Thanks
Philip
I'm scraping many years of rust & barnacles off of my C skills, and
I'm stuck at my first knotty and interesting problem.
I'm writing some code that needs to be cross platform and it uses
several typdef-ed numeric types. For instance, a key_t could be typdef-
ed as an int, ulong, etc. I need to be able to figure out what the
maximum value is that can be stuffed into the key_t and other types.
I've read some of the other threads on this problem[1] and there seems
to be no straightforward solution. Can someone help me understand why
the code below not work? (Please ignore the dodgy assumption in the
printf() that long long is supported.)
#include <stdio.h>
typedef long foo_t; // This represents my unknown type
int main (int argc, char const *argv[])
{
foo_t test_value;
foo_t max = 127;
int found = 0;
while (!found) {
test_value = (max * 2) + 1;
if ( (test_value <= max) || (test_value != ((max * 2) + 1)))
// overflow!
found = 1;
else
max = test_value;
}
printf("max: %llu\n", (unsigned long long)max);
return 0;
}
[1] Some previous threads on the subject:
http://groups.google.com/group/comp.lang.c/browse_thread/thread/d6f967e56fa87617
http://groups.google.com/group/comp.lang.c/browse_thread/thread/84628b61f288bcb2
Thanks
Philip