C Inetrview Question and Answer Set-7

| Thursday 9 June 2011

Characters and Strings

7.1: How can I get the numeric (character set) value corresponding to a character, or vice versa?

The obvious way is to write a function to do the conversion. (Error checking has been omitted for brevity.)
int ctoi(char c) {
        static unsigned char *ary;
        /* initialize the array */
        if (!ary) {
               int i;
 
               ary = malloc(UCHAR_MAX + 2);
               for (i = 0; i < UCHAR_MAX + 1; ++i) {
                       ary[i] = i;
               }
               ary[UCHAR_MAX + 1] = '\0';
        }
        if (c) {
               unsigned char *t;
 
               /* we have to skip the leading NUL */
               t = strchr(ary + 1, c);
               if (!t)
                       return 0;
               return t - ary;
        } else {
               /* special case for NUL character */
               return 0;
        }
}
There are various clever tricks you can use to get around writing the function, but most are too complicated for beginners.

Boolean Expressions and Variables

8.1: What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values?

int (*)(int, char **) makes a good boolean type. You can use main for true, and exit for false. On some compilers, you may need to cast exit() to an appropriate type.

8.2: Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered ``true'' in C? What if a built-in boolean or relational operator ``returns'' something other than 1?

Very good! For instance, one program I saw used
#define TRUE(x) ((x) & 0x100)
for compatability with a specific release of a FORTRAN compiler, which used 0 for .FALSE. and 256 for .TRUE. - this allowed them to change their code with every new release of the FORTRAN compiler, and kept them alert to changes. This has no relationship to the boolean or logical operators in C, which always return 0 or 1.

8.3: What is truth?

It is not a saffron-robed monk, pissing in the snow.

0 comments:

Post a Comment

Popular Posts

Company Placement Papers

 

Copyright © 2010 All Question Papers Blogger Template by Dzignine