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

162⟩ What are pragmas and what are they good for?

The #pragma directive provides a single, well-defined ``escape hatch'' which can be used for all sorts of (nonportable) implementation-specific controls and extensions: source listing control, structure packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc.

 116 views

163⟩ What is the correct declaration of main?

There are two valid declarations:

int main(void)

int main(int argc, char **argv)

although they can be written in a variety of ways. The second parameter may be declared char *argv[] , you can use any names for the two parameters, and you can use old-style syntax:

int main()

int main(argc, argv)

int argc; char **argv;

 125 views

164⟩ Can you mix old-style and new-style function syntax?

Doing so is legal (and can be useful for backwards compatibility), but requires a certain amount of care . Modern practice, however, is to use the prototyped form in both declarations and definitions. (The old-style syntax is marked as obsolescent, so official support for it may be removed some day.)

 120 views

165⟩ What is the ANSI C Standard?

In 1983, the American National Standards Institute (ANSI) commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as ANS X3.159-1989 on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardized existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the controversial trigraph sequences). The ANSI C standard also formalized the C run-time library support routines.

A year or so later, the Standard was adopted as an international standard, ISO/IEC 9899:1990, and this ISO Standard replaced the earlier X3.159 even within the United States (where it was known as ANSI/ISO 9899-1990 [1992]). As an ISO Standard, it is subject to ongoing revision through the release of Technical Corrigenda and Normative Addenda.

In 1994, Technical Corrigendum 1 (TC1) amended the Standard in about 40 places, most of them minor corrections or clarifications, and Normative Addendum 1 (NA1) added about 50 pages of new material, mostly specifying new library functions for internationalization. In 1995, TC2 added a few more minor corrections.

Most recently, a major revision of the Standard, ``C99'', has been completed and adopted.

 117 views

166⟩ How can I list all of the predefined identifiers?

There's no standard way, although it is a common need. gcc provides a -dM option which works with -E, and other compilers may provide something similar. If the compiler documentation is unhelpful, the most expedient way is probably to extract printable strings from the compiler or preprocessor executable with something like the Unix strings utility. Beware that many traditional system-specific predefined identifiers (e.g. ``unix'') are non-Standard (because they clash with the user's namespace) and are being removed or renamed. (In any case, as a general rule, it's considered wise to keep conditional compilation to a minimum.)

 101 views

167⟩ How can I use a preprocessorif expression to ?

How can I use a preprocessor #if expression to tell whether a machine's byte order is big-endian or little-endian?

You probably can't. The usual techniques for detecting endianness involve pointers or arrays of char, or maybe unions, but preprocessor arithmetic uses only long integers, and there is no concept of addressing. Another tempting possibility is something like #if 'ABCD' == 0x41424344 but this isn't reliable, either. At any rate, the integer formats used in preprocessor #if expressions are not necessarily the same as those that will be used at run time. Are you sure you need to know the machine's endianness explicitly? Usually it's better to write code which doesn't care

 98 views

168⟩ Is there anything like an ifdef for typedefs?

Unfortunately, no. (There can't be, because types and typedefs haven't been parsed at preprocessing time.) You may have to keep sets of preprocessor macros (e.g. MY_TYPE_DEFINED) recording whether certain typedefs have been declared.

 98 views

169⟩ What are the complete rules for header file searching?

The exact behavior is implementation-defined (which means that it is supposed to be documented; Typically, headers named with <> syntax are searched for in one or more standard places. Header files named with "" syntax are first searched for in the ``current directory,'' then (if not found) in the same standard places. (This last rule, that "" files are additionally searched for as if they were <> files, is the only rule specified by the Standard.)

Another distinction is the definition of ``current directory'' for "" files. Traditionally (especially under Unix compilers), the current directory is taken to be the directory containing the file containing the #include directive. Under other compilers, however, the current directory is the directory in which the compiler was initially invoked. (Compilers running on systems without directories or without the notion of a current directory may of course use still different rules.)

It is also common for there to be a way (usually a command line option involving capital I, or maybe an environment variable) to add additional directories to the list of standard places to search. Check your compiler documentation.

 109 views

171⟩ What is the right type to use for Boolean values in C? Is there a standard type? Should I use #defines or enums for the true and false values?

Traditionally, C did not provide a standard Boolean type, partly and partly to allow the programmer to make the appropriate space/time tradeoff. (Using an int may be faster, while using char may save data space. Smaller types may make the generated code bigger or slower, though, if they require lots of conversions to and from int.)

However, C99 does define a standard Boolean type, as long as you include <stdbool.h>.

If you decide to define them yourself, the choice between #defines and enumeration constants for the true/false values is arbitrary and not terribly interestingUse any of

#define TRUE 1 #define YES 1

#define FALSE 0 #define NO 0

enum bool {false, true}; enum bool {no, yes};

or use raw 1 and 0, as long as you are consistent within one program or project. (An enumeration may be preferable if your debugger shows the names of enumeration constants when examining variables.)

You may also want to use a typedef:

typedef int bool;

or

typedef char bool;

or

typedef enum {false, true} bool;

Some people prefer variants like

#define TRUE (1==1)

#define FALSE (!TRUE)

or define ``helper'' macros such as

#define Istrue(e) ((e) != 0)

 130 views

172⟩ Why does not strcat(string, "!"); work?

There is a very real difference between characters and strings, and strcat concatenates strings.

A character constant like '!' represents a single character. A string literal between double quotes usually represents multiple characters. A string literal like "!" seems to represent a single character, but it actually contains two: the ! you requested, and the which terminates all strings in C.

Characters in C are represented by small integers corresponding to their character set values Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append a ! to a string, use

strcat(string, "!");

 108 views

173⟩ Why is not a pointer null after calling free? How unsafe is it to use (assign, compare) a pointer value after it is been freed?

When you call free, the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller probably remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments. A pointer value which has been freed is, strictly speaking, invalid, and any use of it, even if it is not dereferenced (i.e. even if the use of it is a seemingly innocuous assignment or comparison), can theoretically lead to trouble. (We can probably assume that as a quality of implementation issue, most implementations will not go out of their way to generate exceptions for innocuous uses of invalid pointers, but the Standard is clear in saying that nothing is guaranteed, and there are system architectures for which such exceptions would be quite natural.)

When pointer variables (or fields within structures) are repeatedly allocated and freed within a program, it is often useful to set them to NULL immediately after freeing them, to explicitly record their state.

 158 views

174⟩ How can I dynamically allocate arrays?

The equivalence between arrays and pointers allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing

#include <stdlib.h>

int *dynarray;

dynarray = malloc(10 * sizeof(int));

(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the ``array''

 110 views

176⟩ What is wrong with this initialization?

What's wrong with this initialization?

char *p = malloc(10);

My compiler is complaining about an ``invalid initializer'', or something.

Is the declaration of a static or non-local variable? Function calls are allowed in initializers only for automatic variables (that is, for local, non-static variables).

 108 views

177⟩ How can this be legal C?

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

Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for any two expressions a and e, as long as one of them is a pointer expression and one is integral. The ``proof'' looks like

a[e]

*((a) + (e)) (by definition)

*((e) + (a)) (by commutativity of addition)

e[a] (by definition)

This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest .

Since strings in C are arrays of char, the expression "abcdef"[5] is perfectly legal, and evaluates to the character 'f'. You can think of it as a shorthand for

char *tmpptr = "abcdef";

... tmpptr[5] ...

 126 views

178⟩ Is a pointer a kind of array?

I'm still mystified. Is a pointer a kind of array, or is an array a kind of pointer?

An array is not a pointer, nor vice versa. An array reference (that is, any mention of an array in a value context), turns into a pointer

There are perhaps three ways to think about the situation:

1. Pointers can simulate arrays

2. There's hardly such a thing as an array (it is, after all, a ``second-class citizen''); the subscripting operator [] is in fact a pointer operator.

3. At a higher level of abstraction, a pointer to a block of memory is effectively the same as an array (though this says nothing about other uses of pointers).

But, to reiterate, here are two ways not to think about it:

4. ``They're completely the same.''

5. ``Arrays are constant pointers.'

 125 views

179⟩ Why ca not I do something like this?

Why can't I do something like this?

extern char *getpass();

char str[10];

str = getpass("Enter password: ");

Arrays are ``second-class citizens'' in C; one upshot of this prejudice is that you cannot assign to them . When you need to copy the contents of one array to another, you must do so explicitly. In the case of char arrays, the strcpy routine is usually appropriate:

strcpy(str, getpass("Enter password: "));

(When you want to pass arrays around without copying them, you can use pointers and simple assignment.

 115 views

180⟩ How do I get a null pointer in my programs?

With a null pointer constant.

According to the language definition, an ``integral constant expression with the value 0'' in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal:

char *p = 0;

if(p != 0)

However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 ``means'' a null pointer. To generate a null pointer in a function call context, an explicit cast may be required, to force the 0 to be recognized as a pointer. For example, the Unix system call execl takes a variable-length, null-pointer-terminated list of character pointer arguments, and is correctly called like this:

execl("/bin/sh", "sh", "-c", "date", (char *)0);

If the (char *) cast on the last argument were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong; When function prototypes are in scope, argument passing becomes an ``assignment context,''

 133 views