C Programming

  Home  Computer Programming  C Programming


“C Programming Interview Questions and Answers will guide you that C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories and C language is for use with the Unix operating system. If you are developer and need to update your software development knowledge regarding basic and advance C programming or need to prepare for a job interview? Check out this collection of basic and advance C programing Interview Questions and Answers.”



221 C Programming Questions And Answers

81⟩ How do I read the arrow keys? What about function keys?

Terminfo, some versions of termcap, and some versions of curses have support for these non-ASCII keys. Typically, a special key sends a multicharacter sequence (usually beginning with ESC, '33'); parsing these can be tricky. (curses will do the parsing for you, if you call keypad first.)

Under MS-DOS, if you receive a character with value 0 (not '0'!) while reading the keyboard, it's a flag indicating that the next character read will be a code indicating a special key. See any DOS programming guide for lists of keyboard scan codes. (Very briefly: the up, left, right, and down arrow keys are 72, 75, 77, and 80, and the function keys are 59 through 68.)

 182 views

82⟩ How do I send escape sequences to control a terminal or other device?

If you can figure out how to send characters to the device at all , it's easy enough to send escape sequences. In ASCII, the ESC code is 033 (27 decimal), so code like

fprintf(ofd, "33[J");

sends the sequence ESC [ J .

Some programmers prefer to parameterize the ESC code, like this:

#define ESC 033

fprintf(ofd, "%c[J", ESC);

 181 views

83⟩ How can I make it pause before closing the program output window?

I'm compiling some test programs on a windows-based system, and the windows containing my program's output are closing so quickly after my program calls exit that I can't see the output. How can I make it pause before closing?

After wondering why the author of your compiler's run-time system didn't take care of this for you, simply add the lines

printf("Hit RETURN to exit"n");

fflush(stdout); (void)getchar();

just before the end of your program. (If you want to wait for any keystroke, not just the RETURN key

 172 views

84⟩ I need code to parse and evaluate expressions.

Two available packages are ``defunc,'' posted to comp.sources.misc in December, 1993 (V41 i32,33), to alt.sources in January, 1994, and available from sunsite.unc.edu in pub/packages/development/libraries/defunc-1.3.tar.Z, and ``parse,'' at lamont.ldgo.columbia.edu. Other options include the S-Lang interpreter, available via anonymous ftp from amy.tch.harvard.edu in pub/slang, and the shareware Cmm (``C-minus-minus'' or ``C minus the hard stuff'').

 178 views

85⟩ How can I find out if there are characters available for reading?

How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available?

These, too, are entirely operating-system-specific. Some versions of curses have a nodelay function. Depending on your system, you may also be able to use ``nonblocking I/O'', or a system call named select or poll, or the FIONREAD ioctl, or c_cc[VTIME], or kbhit, or rdchk, or the O_NDELAY option to open or fcntl. You can also try setting an alarm to cause a blocking read to time out after a certain interval (under Unix, look at alarm, signal, and maybe setitimer).

If what you're trying to do is read input from several sources without blocking, you will definitely want to use some kind of a ``select'' call, because a busy-wait, polling loop is terribly inefficient on a multitasking system.

 173 views

86⟩ How can I display a percentage-done indication that updates itself in place, or show one of those twirling baton progress indicators?

These simple things, at least, you can do fairly portably. Printing the character 'r' will usually give you a carriage return without a line feed, so that you can overwrite the current line. The character 'b' is a backspace, and will usually move the cursor one position to the left.

Using these characters, you can print a percentage-done indicator:

for(i = 0; i < lotsa; i++) {

printf("r%3d%%", (int)(100L * i / lotsa));

fflush(stdout);

do_timeconsuming_work();

}

printf("ndone.n");

or a baton:

printf("working: ");

for(i = 0; i < lotsa; i++) {

printf("%cb", "|/-"[i%4]);

fflush(stdout);

do_timeconsuming_work();

}

printf("done.n");

 187 views

87⟩ Dont ANSI function prototypes render lint obsolete?

Not really. First of all, prototypes work only if they are present and correct; an inadvertently incorrect prototype is worse than useless. Secondly, lint checks consistency across multiple source files, and checks data declarations as well as functions. Finally, an independent program like lint will probably always be more scrupulous at enforcing compatible, portable coding practices than will any particular, implementation-specific, feature- and extension-laden compiler.

If you do want to use function prototypes instead of lint for cross-file consistency checking, make sure that you set the prototypes up correctly in header files.

 173 views

88⟩ Where can I get an ANSI-compatible lint?

Products called PC-Lint and FlexeLint are available from Gimpel Software.

The Unix System V release 4 lint is ANSI-compatible, and is available separately (bundled with other C tools) from UNIX Support Labs or from System V resellers.

Another ANSI-compatible lint (which can also perform higher-level formal verification) is Splint (formerly lclint).

In the absence of lint, many modern compilers do attempt to diagnose almost as many problems as lint does. (Many netters recommend gcc -Wall -pedantic

 173 views

89⟩ How can I shut off the warning ...

How can I shut off the ``warning: possible pointer alignment problem'' message which lint gives me for each call to malloc?

A modern lint shouldn't be complaining about this.

Once upon a time, lint did not and could not know that malloc ``returns a pointer to space suitably aligned for storage of any type of object.'' There were various kludgey workarounds for this problem, but today, the void * type exists precisely to encapsulate the notion of a ``generic'' pointer, and an ANSI-compatible lint should understand this.

 162 views

90⟩ What is Hungarian Notation? Is it worthwhile?

Hungarian Notation is a naming convention, invented by Charles Simonyi, which encodes information about a variable's type (and perhaps its intended use) in its name. It is well-loved in some circles and roundly castigated in others. Its chief advantage is that it makes a variable's type or intended use obvious from its name; its chief disadvantage is that type information is not necessarily a worthwhile thing to carry around in the name of a variable.

 178 views

91⟩ People always say that good style is important

People always say that good style is important, but when they go out of their way to use clear techniques and make their programs readable, they seem to end up with less efficient programs. Since efficiency is so important, isn't it necessary to sacrifice some style and readability?

It's true that grossly inefficient programs are a problem, but the blind zeal with which many programmers often chase efficiency is also a problem. Cumbersome, obscure programming tricks not only destroy readability and maintainability, but they may actually lead to slimmer long-term efficiency improvements than would more appropriate design or algorithm choices. With care, it is possible to design code which is both clean and efficient.

 172 views

92⟩ I just typed in this program, and it is acting strangely. Can you see anything wrong with it?

See if you can run lint first (perhaps with the -a, -c, -h, -p or other options ). Many C compilers are really only half-compilers, taking the attitude that it's not their problem if you didn't say what you meant, or if what you said is virtually guaranteed not to work. (But do also see if your compiler has extra warning levels which can be optionally requested.)

 182 views

93⟩ Should I use symbolic names like TRUE and FALSE for Boolean constants, or plain 1 and 0?

It's your choice. Preprocessor macros like TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change. It's a matter of style, not correctness, whether to use symbolic names or raw 1/0 values.

On the one hand, using a symbolic name like TRUE or FALSE reminds the reader that a Boolean value is involved. On the other hand, Boolean values and definitions can evidently be confusing, and some programmers feel that TRUE and FALSE macros only compound the confusion.

 187 views

94⟩ If NULL and 0 are equivalent as null pointer constants, which should I use?

Many programmers believe that NULL should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding NULL and 0 is only compounded by hiding 0 behind a macro, and prefer to use unadorned 0 instead. There is no one right answer. C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's.

It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void *)0), which will not work at all in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition

#define NUL ''

if you must.

 192 views

95⟩ I came across some code that puts a (void) cast before each call to printf. Why?

printf does return a value (the number of characters printed, or an error code), though few programs bother to check the return values from each call. Since some compilers (and lint) will warn about discarded return values, an explicit cast to (void) is a way of saying ``Yes, I've decided to ignore the return value from this call, but please continue to warn me about other (perhaps inadvertently) ignored return values.'' It's also common to use void casts on calls to strcpy and strcat, since the return value is never surprising.

 185 views

96⟩ I have seen function declarations that look like this

I've seen function declarations that look like this:

extern int func __((int, int));

What are those extra parentheses and underscores for?

They're part of a trick which allows the prototype part of the function declaration to be turned off for a pre-ANSI compiler. Somewhere else is a conditional definition of the __ macro like this:

#ifdef __STDC__

#define __(proto) proto

#else

#define __(proto) ()

#endif

The extra parentheses in the invocation

extern int func __((int, int));

are required so that the entire prototype list (perhaps containing many commas) is treated as the single argument expected by the macro.

 187 views

97⟩ Why do some people write if(0 == x) instead of if(x == 0)?

It's a trick to guard against the common error of writing

if(x = 0)

If you're in the habit of writing the constant before the ==, the compiler will complain if you accidentally type

if(0 = x)

Evidently it can be easier for some people to remember to reverse the test than to remember to type the doubled = sign. (To be sure, accidentally using = instead of == is a typo which even the most experienced C programmer can make.)

On the other hand, some people find these reversed tests ugly or distracting, and argue that a compiler should warn about if(x = 0). (In fact, many compilers do warn about assignments in conditionals, though you can always write if((x = expression)) or if((x = expression) != 0) if you really mean it.)

 180 views

98⟩ Here is a neat trick for checking whether two strings are equal

Here's a neat trick for checking whether two strings are equal:

if(!strcmp(s1, s2))

Is this good style?

It is not particularly good style, although it is a popular idiom. The test succeeds if the two strings are equal, but the use of ! (``not'') suggests that it tests for inequality.

Another option is to define a macro:

#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)

which you can then use like this:

if(Streq(s1, s2))

Another option (which borders on preprocessor abuse;is to define

#define StrRel(s1, op, s2) (strcmp(s1, s2) op 0)

after which you can say things like

if(StrRel(s1, ==, s2)) ...

if(StrRel(s1, !=, s2)) ...

if(StrRel(s1, >=, s2)) ...

 186 views

99⟩ How should functions be apportioned among source files?

Usually, related functions are put together in one file. Sometimes (as when developing libraries) it is appropriate to have exactly one source file (and, consequently, one object module) per independent function. Other times, and especially for some programmers, numerous source files can be cumbersome, and it may be tempting (or even appropriate) to put most or all of a program in a few big source files. When it is desired to limit the scope of certain functions or global variables by using the static keyword, source file layout becomes more constrained: the static functions and variables and the functions sharing access to them must all be in the same file.

In other words, there are a number of tradeoffs, so it is difficult to give general rules.

 164 views

100⟩ What is the best style for code layout in C?

While providing the example most often copied, also supply a good excuse for disregarding it:

The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently.

It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be ``perfect.'' If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R.

Each of the various popular styles has its good and bad points. Putting the open brace on a line by itself wastes vertical space; combining it with the following line makes it hard to edit; combining it with the previous line prevents it from lining up with the close brace and may make it harder to see.

Indenting by eight columns per level is most common, but often gets you uncomfortably close to the right margin (which may be a hint that you should break up the function). If you indent by one tab but set tabstops at something other than eight columns, you're requiring other people to read your code with the same software setup that you used. .

The elusive quality of ``good style'' involves much more than mere code layout details; don't spend time on formatting to the exclusion of more substantive code quality issues.

 176 views