C Interview Questions and Answers


What is the difference between far and near in C?

Some compilers for PC compatibles use two types of pointers. near pointers are 16
bits long and can address a 64KB range. far pointers are 32 bits long and can address
a 1MB range.

Near pointers operate within a 64KB segment. There’s one segment for function
addresses and one segment for data. far pointers have a 16-bit base (the segment
address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is
effectively 20 bits long. Before you compile your code, you must tell the compiler
which memory model to use. If you use a smallcode memory model, near pointers are
used by default for function addresses.

That means that all the functions need to fit in one 64KB segment. With a large-code
model, the default is to use far function addresses. You’ll get near pointers
with a small data model, and far pointers with a large data model. These are just
the defaults; you can declare variables and functions as explicitly near or far.

far pointers are a little slower. Whenever one is used, the code or data segment
register needs to be swapped out. far pointers also have odd semantics for arithmetic
and comparison. For example, the two far pointers in the preceding example point
to the same address, but they would compare as different! If your program fits in
a small-data, small-code memory model, your life will be easier.

Posted by:Richards