Showing posts with label C Inetrview Question and Answer. Show all posts
Showing posts with label C Inetrview Question and Answer. Show all posts

C Inetrview Question and Answer Set-9

0
| Thursday, 9 June 2011

ANSI C

10.1: What is the ``ANSI C Standard?''

A whiny bunch of lusers who haven't written as many books as Herbert Schildt.

10.2: How can I get a copy of the Standard?

Use a copier.

10.3: Does anyone have a tool for converting old-style C programs to ANSI C, or vice versa, or for automatically generating prototypes?

A router helps, but your best bet is still the band saw. Quick, efficient, and powerful.

10.4: I'm trying to use the ANSI ``stringizing'' preprocessing operator # to insert the value of a symbolic constant into a message, but it keeps stringizing the macro's name rather than its value.

This is because "3" is not a legal integral constant in C - it's a string constant.

10.5: I don't understand why I can't use const values in initializers and array dimensions, as in

        const int n = 7;
        int a[n];
Because you're not using C++.

10.6: What's the difference between ``char const *p'' and ``char * const p''?

One `` '' character. There are some trivial differences having to do with the distinction between a pointer to a constant, and a constant pointer, but since you can cast either to a (char *) it hardly matters.

10.7: Can I declare main as void, to shut off these annoying ``main returns no value'' messages? (I'm calling exit(), so main doesn't return.)

Certainly. You can also declare it as double. It may not compile, or it may crash, but who cares? No lousy bunch of whining lusers is going to tell *you* what to do.

10.8: Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance?

Because none of the members of the committee had names over six letters, or in which letters other than the first were capitalized.

10.9: What is the difference between memcpy and memmove?

memmove moves memory, and memcpy copies it. memmove may not be supported on machines without internal robot arms. Do not use memmove while the machine is powered up - you can destroy your memory.

10.10: Why won't the Frobozz Magic C Compiler, which claims to be ANSI compliant, accept this code? I know that the code is ANSI, because gcc accepts it.

The Frobozz Magic Company lies through its teeth. Consider: does Flood Control Dam #3 actually control floods? Didn't think so. The wands are excellent for making useless via casts of Float, though.

10.11: Why can't I perform arithmetic on a void * pointer?

You're too big and clumsy. When you try to push the numbers together, you lose your balance. Perhaps you should get some angels from the rave over on pin 3.

10.12: What are #pragmas and what are they good for?

They are useful ways to eliminate compiler features which are not helpful to your goals; contrast #utility, which introduces useful compiler features, and #absolutist, which introduces those compiler features believed to be right. #relativist is supported by some compilers.

10.13: What does ``#pragma once'' mean? I found it in some header files.

It means that your program will only run once; it's used to create ``crippled demos''.

10.14: People seem to make a point of distinguishing between implementation-defined, unspecified, and undefined behavior. What's the difference?

There isn't really one; people just enjoy flaming over nits. (To be technical, one has a hyphen, one has a space, and one is a single word.)

10.15: Is C an acronym?

Yes, it stands for ``C''. It's another of those funky recursive acronyms

C Inetrview Question and Answer Set-8

0
|

C Preprocessor

9.1: How can I use a preprocessor #if expression to tell if a machine is big-endian or little-endian?

#ifdef __BIG_ENDIAN should work on all known machines; Borland defines it.

9.2: I've got this tricky processing I want to do at compile time and I can't figure out a way to get cpp to do it.

Poor baby.

9.3: How can I list all of the pre-#defined identifiers?

#define __ALL_CPP_IDS - put this in a source file, and run it through your C preprocessor.

9.4: How can I write a cpp macro which takes a variable number of arguments?

Try something like this:
#define add(x) (x)
#define add(x, y) (x + y)
#pragma induction add

9.5: Shouldn't the following code:

        #define ROSE 1
        #define CHRYSANTHEMUM 2
        #define RHODODENDRON 3
        #define WATER_LILY 4
        printf("%d\n", CHRYSATHNEMUM);
print ``2''?
You misspelled CHRYSANTHEMUM. Use abbreviations for long flower names in C code.

C Inetrview Question and Answer Set-7

0
|

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.

C Inetrview Question and Answer Set-6

0
|
6

Memory Allocation

6.1: Why doesn't this fragment work?

        char *answer
        printf("Type something:\n");
        gets(answer);
        printf("You typed \"%s\"\n", answer);
The semicolon after ``answer'' is missing.

6.2: I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.

You probably returned a pointer to a local array. That doesn't work. Try using a temporary file, instead. For instance:
char *getstr(void) {
        FILE *fp = tmpfile();
        fputs(gets(NULL), fp);
        return (char *) fp;
}

6.3: Why does some code carefully cast the values returned by malloc to the pointer type being allocated?

In interrupt-riddled code, it may be necessary to cast values to force the CPU to resolve pointer types.

6.4: You can't use dynamically-allocated memory after you free it, can you?

Yes. However, what happens when you do is not clearly defined.

6.5: How does free() know how many bytes to free?

Interrupt 41h. On macs, amigas, and other ``big-endian'' processors, that would be interrupt 14h; be wary of portability problems.

6.6: So can I query the malloc package to find out how big an allocated block is?

Not exactly; because the objects are dynamically allocated, their size can change at run time, so this will not be reliable. If you restrict your allocation to allocating sizeof(void *) bytes at a time, you will find that you can use sizeof() to get the size of a block, in the obvious way.

6.7: I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I have to free each subsidiary pointer first?

No. You just have to keep track of them somewhere else also.

6.8: Was Proust's masterwork, A Remembrance of Things Past, the basis for the C library's allocation scheme, based largely on contextual analysis?

The standard does not specify an allocation scheme; the famous author the allocation scheme is based on is implementation specified. Proust is a common choice, however.

6.9: I have a program which mallocs but then frees a lot of memory, but memory usage (as reported by ps) doesn't seem to go back down.

You're probably not freeing the memory completely. Try replacing 'free(foo);' with
free(foo);
free(foo);
free(foo);
in case the first free() frees the memory only partially. (Unix wizards may recognize the parallel with syncing three times before rebooting.)
Alternatively, free(foo) + 4; may free the remaining four bytes. (Before using this, make sure realloc(foo, 0) returned 4).

C Inetrview Question and Answer Set-5

0
|

Arrays and Pointers

5.1: I had the definition char a[6] in one source file, and in another I declared extern char a[]. Why did it work?

The declaration extern char a[] simply matches the actual definition. The type ``array-of-type-T'' is the same as ``array-of-type-T.'' Go ahead and use extern char a[]. (For greater portability, use it in both files, not only in one of them.)

5.2: But I heard that char a[] was different from char a[6].

This is true. However, the declaration a[] is compatible with the definition a[6].

5.3: So what is meant by the ``equivalence of pointers and arrays'' in C?

Very little.

5.4: Then why are array and pointer declarations interchangeable as function formal parameters?

Classism. We consider arrays ``second class objects''. They don't vote, and they get treated as pointers. Additionally, they're merely objects, not citizens. Marx wrote about this a lot.

5.5: Why doesn't sizeof properly report the size of an array which is a parameter to a function?

Part of the ANSI conspiracy to restrict people to passing pointers; this was undertaken after the first discovery that passing large arrays recursively could cause crashes. Since then, with the passing of MS-DOS, it has become a non-issue; since all serious machines have virtual memory, you can pass as much data as you want on the stack without detectable problems.

5.6: Someone explained to me that arrays were really just constant pointers.

Cool. Someone I know says he saw Elvis in a local bar.
5.7: Practically speaking, what is the difference between arrays and pointers?
About the difference between alcohol and marijuana; they have different characteristics, and that's not a problem if you don't mix them too carelessly.

5.8: I came across some ``joke'' code containing the ``expression'' 5["abcdef"]. How can this be legal C?

It was added to allow people to avoid the character constant 'f' which may not be available on some systems. (Actually, it's a side-effect of the equivalence of arrays and pointers.)

5.9: How would I initialize an entire array from standard input?

You have to use a loop. For instance, the following code reads the numbers zero through 99 into the array a.
for (i = 0; i < 100; ++i)
        a[i] = (scanf, ("%d", i));
Make sure to include <stdio.h>, or this may not work.

C Inetrview Question and Answer Set-4

0
|

Null Statements

4.1: What is this infamous null statement, anyway?

A null statement is an expression statement consisting solely of the terminating semicolon. The optional expression is dropped. It can be distinguished from any other statement by byte count or study of side-effects.

4.2: How do I ``get'' a null statement in my programs?

In ANSI C, there are six types of statements; labeled statements, compound statements, expression-statements, selection statements, iteration statements, and jump statements. All of them, except the jump and expression statments, are defined in terms of optional preceeding text, and other statements. The jump statements are never null statements. An expression statement is considered to be ``a null statement'' if the optional expression part of it has been left out. A null statement can appear on its own, or (most frequently) as the statement body of an iteration statement. These two null statements are equivalent, though neither of them is equivalent to any non-null statement. [*]
You may accidentally get a null statement by deleting the body of a non-null statement.
[*] Actually, they are functionally equivalent to a large set of non-null statements, namely, those with no side-effects. However, the FDA has yet to approve any such, as their lack of side effects is conjectured, and not clinically proven. This applies only to the ANSI standard, and not the ISO standard, as the FDA has no jurisdiction outside the U.S.

4.3: Is there more than one null statement?

Sort of. You can use ``;'', ``0;'', or ``1;'' - they will all act like a null statement. Only the first is a ``true'' null statement (all bits zero). They are basically equivalent. Note that (void *) 0; is a null statement of type pointer to void, for instance.

4.4: But I thought { } was a null statement!

No. { statement-list[opt] } is a compound statement. An empty block is not the same as a null statement, however, although it can be used in many of the same places. It's really a null block. (You can convert it with a cast, but it's not directly compatible. For instance, you can't use a null block as one of the controlling statements of a for loop.)

4.5: I use the statement #define NULLSTMT(F) (F) ; to allow me to cast a null statement to an appropriate type.

This trick, though popular in some circles, does not buy much. The resulting code is invalid, and will not compile. This (in the author's opinion) outweighs any arguable type consistency. It may be more common in industrial code. If it becomes common practice, C++ will probably legalize it.

4.6: I use the statement #define NULLSTMT(F) (F) 0; to allow me to cast a null statement to an appropriate type.

This trick will likely work, but think: what does it really buy you? Mostly, it will indicate to even the most casual observer that you are shakey on the concept of null statements, making it harder for them to check your code.

4.7: But wouldn't it be better to use ; (rather than 0;) in case the value of 0 changes, perhaps on a machine with nonzero no-op instructions?

No. The '0' of '0;' is not evaluated as an instruction, rather, it is just ignored. The only reason to use '0;' instead of ';' is to help keep 1-heavy code properly balanced (in C, which uses binary representations for numbers, it is possible for code to become unbalanced; an unbalanced binary tree is a common source of poor performance.

4.8: Is a null statement a null pointer?

No. A null pointer is a pointer where all of the address bits are zero (no matter what the segment bits are), and can be obtained by typing '(char *) (int) 0'. A null statement is not a pointer to anything. They are not interchangeable, although you can combine them to get an effectively-null statement, such as NULL;. This does not buy you anything.

4.9: I'm still confused. I just can't understand all this null statement stuff.

Follow these two simple rules:
1.      When you don't want to do anything in source code, don't write it.
2.      If you need a null statement to round out an expression, use an unadorned ; to provide it.
3.      Send large donations, checks, and money orders to the author of the FAQ, or the moderator of the group, whichever you prefer. Then, cross the top question off the FAQ, answer the question at the bottom, and mail it to three people. Within two weeks, you will receive 729 answers to various questions! Do not break the chain; Emily Postnews broke the chain, and now no one listens to her. 

C Inetrview Question and Answer Set-3

0
|

Expressions

3.1: Why doesn't the code a[i] = i++; work?

You didn't declare either i or a.

3.2: Under my compiler, the code

        int i = 7;
        printf("%d\n", i++ * i++);
prints 49. Regardless of the order of evaluation, shouldn't it print 56?
No. The only logical answer would be 81 - two postfix ++'s are automatically converted to prefix.

3.3: I've experimented with the code

        int i = 2;
        i = i++;

on several compilers. Some gave i the value 2, some gave 3, but one gave 4. I know the behavior is undefined, but how could it give 4?

Because i is 2, the loop is e     - 6 -xecuted twice.

3.4: People keep saying the behavior is undefined, but I just tried it on an ANSI-conforming compiler, and got the results I expected.

They were probably wrong. Flame them mercilessly. Be sure before you do that your compiler is really ANSI conforming, though. If it turns out you were wrong, they get a legal claim on your first-born.

3.5: Can I use explicit parentheses to force the order of evaluation I want? Even if I don't, doesn't precedence dictate it?

No. To force order of evaluation, you must threaten it. Take the comma operator hostage. Using it, you can force the other operators to do what you want.

3.6: But what about the &&, ||, and comma operators? I see code like ``if((c = getchar()) == EOF || c == '\n')'' ...

As noted, once you've captured the comma operator, the others become docile.

3.7: If I'm not using the value of the expression, should I use i++ or ++i to increment a variable?

++i. Only losers and idiots use i++. This is different if your native language would idiomatically use ``i increment'', but in English and related languages, you must use ++i. Note that a modern program must use both, dependent on the current locale.

3.8: Why is i = ++i undefined?

Because it is unclear whether it is shorthand for i = 42; or i = (char *) "forty two";.
Given the ambiguity, the standards committee decided to leave it undefined.

C Inetrview Question and Answer Set-2

0
|

Structures, Unions, and Enumerations

2.1: What is the difference between an enum and a series of preprocessor #defines?

The enum doesn't require the preprocessor.

2.2: I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not.

K&R I was wrong; they hadn't actually learned C very well before writing the book. Later, Ritchie got a job at Bell Labs, and worked closely with the authors of C, allowing the 2nd edition of the book to be much more accurate. (Kernighan already worked at Bell Labs, as a video game developer.)

2.3: How does struct passing and returning work?

The structures are put into the low part of the VGA card's VRAM. They are then removed before the next video update. This is why struct passing was not supported for a long time; VGA cards were prohibitively expensive.
If you try to pass very large structures on the stack, you may see odd screen graphics.

2.4: Why can't you compare structs?

Compare them to what? A summer's day?

2.5: How can I read/write structs from/to data files?

Loop with putchar. Be careful; if your machine uses signed chars by default, all of the sign bits in your structure elements will be reversed.

2.6: How can I determine the byte offset of a field within a structure?

It's generally 4 times the number of members of the structure. It may be more or less on some machines.

2.7: How can I access structure fields by name at run time?

foo."name" should work. You may need to overload the . operator, which, in turn, may overload your C compiler.

2.8: Why does sizeof report a larger size than I expect for a structure type, as if there was padding at the end?

Because there's padding at the end. Duh.

2.9: My compiler is leaving holes in structures, which is wasting space and preventing ``binary'' I/O to external data files. Can I turn off the padding, or otherwise control the alignment of structs?

Sure. What you do to eliminate the padding in structures is use unions; for intance,
struct foo {
        char c;
        long l;
        char d;
        char e;
        char f;
};
may cause struct foo to be padded to 12 bytes, rather than the correct size of 8. Try
union foo {
        double _d;
        char c, d, e, f;
        long l;
};
which will be 8 bytes. (The double is for alignment.)

2.10: Can I initialize unions?

Depends. They may go on strike when provoked. Luckily, if your program involves air traffic control, the ISO standard guarantees that Ronald Reagan will fire any unions that go on strike, and replace them with structs, which should be close enough.

C Inetrview Question and Answer Set-1

0
|

Declarations and Initializations

1.1: How do you decide which integer type to use?

Use ``short'' when you need to avoid values over 32,767, ``int'' when you want to store integers, ``long'' for long numbers (more than 6 digits), and ``float'' for numbers over 4 billion.

1.2: What should the 64-bit type on new, 64-bit machines be?

int.

1.3: If I write the code int i, j; can I assume that (&i + 1) == &j?

Only sometimes. It's not portable, because in EBCDIC, i and j are not adjacent.
1.4: What's the best way to declare and define global variables?
In headers; this way, you can get link errors when you include the same header twice. Generally, you will have to define a variable everywhere you want to use it, and then declare it someplace so you know what it is.

1.5: What does extern mean in a function declaration?

It refers to a variable which is not actually in your program. For instance,
main() {
        extern int bar;
        printf("%d\n", bar);
        return 0;
}
Will compile without errors because bar is declared as being external. (It won't run, though, because you never assign bar a value.)

1.6: I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one?

With the assignment operator. You were perhaps expecting a screwdriver?

1.7: I've seen different methods used for calling through pointers to functions. What's the story?

In the old days, when Microsoft first invented C, the syntax for calling functions involved more parentheses; this was after their market research indicated that most C programmers would be coming from a Lisp environment. Later, when Kernighan took over the language design (right after AT&T bought Microsoft's language technology), he decided to eliminate the parentheses, but the old form is still allowed.
You do need the parentheses to call a function with more than one argument, for instance,
int (*foo)(char *, ...) = printf;
(*foo)("hello, %s\n", "world!");
needs the parens, but they would not be needed for
foo, "hello, world!\n";
(The ``*'' just means to execute foo, just like the ``*'' on the end of an executable filename in ``ls -F''.)

1.8: What's the auto keyword good for?

Declaring vehicles.

1.9: I can't seem to define a linked list successfully. I tried

        typed struct {
               char *item;
               NODEPTR next;
        } *NODEPTR;
but the compiler gave me error messages. Can't a structure in C contain a pointer to itself?
Not exactly; it can contain a pointer to another structure of the same type. Try:
typedef struct {
        char *item;
        double *next;
} NODEFAKE;
typedef struct {
        char *item;
        NODEFAKE *next;
} NODEPTR;
Make sure that sizeof(NODEPTR) == sizeof(double).
This technique is called a ``backwards reference''.

1.10: How do I enter values using hexadecimal?

long ints can be entered using hexadecimal notation; for instance,
long int foo = 07;
sets foo to hex 7.

1.11: How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?

Well, first you need to know how to declare an array of N items of type T - that's
T foo[N];
Now you need to look at how to declare a pointer to function returning something, say, an object of type S. That's like this:
S (*bar)();
Now assume that S is ``pointer to function returning pointer to char''. We get
(char *) (*)() (*bar)().
So, the whole thing turns out to be (with appropriate parentheses)
(((char)(*))((*)())(((*)((foo)))())([(N)]));
If your compiler complains, break this down into subexpressions.
To call it, just use
foo[i]();
This works because, in C, declaration reflects use, but it's one of those weird distorted mirrors.

Popular Posts

Company Placement Papers

 

Copyright © 2010 All Question Papers Blogger Template by Dzignine