ra****@thisisno tmyrealemail.co m writes:
Thanks to everyone for interesting discussions. To make the group
happy, my next listing has int main and headers declared!!
Here is my solution to Exercise 2.3.
// write htoi, hex to int
#include<stdio. h>
int main(int c, char **v)
The traditional names for the parameters to main() are argc and argv.
Using different names is legal, but a very bad idea; it just makes
your code more difficult to read.
{
int x=-1, htoi();
Putting a function declaration inside a function definition is legal,
but not a good idea. A function declaration with empty parentheses
says that the function takes a fixed but unspecied number and type(s)
of arguments.
Either declare htoi() with a full prototype at file scope (outside main()):
int htoi(char *s);
or move the full definition of htoi() above the definition of main(),
so you don't need a separate declaration.
if(c>1)
x=htoi(v[1]);
if(x>=0)
printf("%d\n", x);
else
printf("Unspeci fied error.\n");
Error messages are normally printed to stderr, not stdout.
You could detect the specific error of invoking main() with no
arguments. Consider something like this:
if (argc <= 1) {
fprintf(stderr, "Usage: %s arg\n", argv[0]);
exit(EXIT_FAILU RE);
}
}
int htoi(char *s)
Consider declaring this static, since it's not used from any other
translation units.
{
char *t=s;
int x=0, y=1;
if(*s=='0' && (s[1]=='x' || s[1]=='X'))
t+=2;
s+=strlen(s);
while(t<=--s) {
if('0' <= *s && *s <= '9')
You can use the isdigit() function for this.
x+=y*(*s - '0');
else if('a' <= *s && *s <= 'f')
x+=y*(*s - 'a' + 10);
else if('A' <= *s && *s <= 'F')
x+=y*(10 + *s - 'A');
You're assuming that the numeric codes for the letters 'a'..'f' and
'A'..'F' are contiguous. This is not guaranteed, and there are
character sets where the alphabet is not contiguous (though in the one
example of this that I know of, 'a'..'f' and 'A'..'F' happen to be
contiguous). Consider using the isxdigit() function.
else
return -1; /* invalid input! */
y<<=4;
}
return x;
}
These are mostly superficial points. I'd take a closer look at the
algorithm, but your use of meaningless single-character identifiers
makes your code difficult to read.
--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"