Showing posts with label of. Show all posts
Showing posts with label of. Show all posts

Wednesday, September 29, 2010

Implementation Issues Of Functions in C,C++

There are a few important things to remember about functions that affect their
efficiency and usability. These issues are the subject of this section.

Parameters and General-Purpose Functions
A general-purpose function is one that will be used in a variety of situations, perhaps
by many different programmers. Typically, you should not base general-purpose
functions on global data. All of the information a function needs should be passed
to it by its parameters. When this is not possible, you should use static variables.
Besides making your functions general purpose, parameters keep your code
readable and less susceptible to bugs resulting from side effects.

Efficiency
Functions are the building blocks of C/C++ and are crucial to all but the simplest
programs. However, in certain specialized applications, you may need to eliminate
a function and replace it with inline code. Inline code performs the same actions as a
function, but without the overhead associated with a function call. For this reason,
inline code is often used instead of function calls when execution time is critical.
Inline code is faster than a function call for two reasons. First, a CALL instruction
takes time to execute. Second, if there are arguments to pass, these have to be placed
on the stack, which also takes time. For most applications, this very slight increase in
execution time is of no significance. But if it is, remember that each function call uses
time that would be saved if the function's code were placed in line. For example, the
following are two versions of a program that prints the square of the numbers from 1
to 10. The inline version runs faster than the other because the function call adds time.
in line function call
#include <stdio.h> #include <stdio.h>
int sqr(int a);
int main(void) int main(void)
{ {
int x; int x;
for(x=1; x<11; ++x) for(x=1; x<11; ++x)
printf("%d", x*x); printf("%d", sqr(x));
return 0; return 0;
} }
int sqr(int a)
{
return a*a;
}
 
Note : In C++, the concept of inline functions is expanded and formalized. In fact, inline
functions are an important component of the C++ language.

Declaring Variable-Length Parameter Lists Of function in C, C++

You can specify a function that has a variable number of parameters. The most
common example is printf() . To tell the compiler that an unknown number of
arguments may be passed to a function, you must end the declaration of its
parameters using three periods. For example, this prototype specifies that func()
will have at least two integer parameters and an unknown number (including 0)
of parameters after that.
int func(int a, int b, ...);
This form of declaration is also used by a function's definition.
Any function that uses a variable number of parameters must have at least one
actual parameter. For example, this is incorrect:
int func(...); /* illegal */

Functions of Type void

One of void's uses is to explicitly declare functions that do not return values. This
prevents their use in any expression and helps avert accidental misuse. For example,
the function print_vertical() prints its string argument vertically down the side of
the screen. Since it returns no value, it is declared as void.
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
Here is an example that uses print_vertical() .
#include <stdio.h>
void print_vertical(char *str); /* prototype */

int main(int argc, char *argv[])
{
if(argc > 1) print_vertical(argv[1]);
return 0;
}
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
One last point: Early versions of C did not define the void keyword. Thus, in
early C programs, functions that did not return values simply defaulted to type int.
Therefore, don't be surprised to see many examples of this in older code.

Monday, September 27, 2010

Scope Rules of Functions in C C++

The scope rules of a language are the rules that govern whether a piece of code knows
about or has access to another piece of code or data.
Each function is a discrete block of code. A function's code is private to that function
and cannot be accessed by any statement in any other function except through a call to
that function. (For instance, you cannot use goto to jump into the middle of another
function.) The code that constitutes the body of a function is hidden from the rest of the
program and, unless it uses global variables or data, it can neither affect nor be affected by other parts of the program. Stated another way, the code and data that are defined
within one function cannot interact with the code or data defined in another function
because the two functions have a different scope.
Variables that are defined within a function are called local variables. A local
variable comes into existence when the function is entered and is destroyed upon
exit. That is, local variables cannot hold their value between function calls. The only
exception to this rule is when the variable is declared with the static storage class
specifier. This causes the compiler to treat the variable as if it were a global variable
for storage purposes, but limits its scope to within the function. (Chapter 2 covers
global and local variables in depth.)
In C (and C++) you cannot define a function within a function. This is why neither
C nor C++ are technically block-structured languages.

Implementation Issues of functions C,C++

There are a few important things to remember about functions that affect their
efficiency and usability. These issues are the subject of this section.

Parameters and General-Purpose Functions
A general-purpose function is one that will be used in a variety of situations, perhaps
by many different programmers. Typically, you should not base general-purpose
functions on global data. All of the information a function needs should be passed
to it by its parameters. When this is not possible, you should use static variables.
Besides making your functions general purpose, parameters keep your code
readable and less susceptible to bugs resulting from side effects.

Efficiency
Functions are the building blocks of C/C++ and are crucial to all but the simplest
programs. However, in certain specialized applications, you may need to eliminate
a function and replace it with inline code. Inline code performs the same actions as a

function, but without the overhead associated with a function call. For this reason,
inline code is often used instead of function calls when execution time is critical.
Inline code is faster than a function call for two reasons. First, a CALL instruction
takes time to execute. Second, if there are arguments to pass, these have to be placed
on the stack, which also takes time. For most applications, this very slight increase in
execution time is of no significance. But if it is, remember that each function call uses
time that would be saved if the function's code were placed in line. For example, the
following are two versions of a program that prints the square of the numbers from 1
to 10. The inline version runs faster than the other because the function call adds time.
in line function call
#include <stdio.h> #include <stdio.h>
int sqr(int a);
int main(void) int main(void)
{ {
int x; int x;
for(x=1; x<11; ++x) for(x=1; x<11; ++x)
printf("%d", x*x); printf("%d", sqr(x));
return 0; return 0;
} }
int sqr(int a)
{
return a*a;
}
In C++, the concept of inline functions is expanded and formalized. In fact, inline
functions are an important component of the C++ language.

Functions of Type void in C,C++

One of void's uses is to explicitly declare functions that do not return values. This
prevents their use in any expression and helps avert accidental misuse. For example,
the function print_vertical() prints its string argument vertically down the side of
the screen. Since it returns no value, it is declared as void.
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
Here is an example that uses print_vertical() .
#include <stdio.h>
void print_vertical(char *str); /* prototype */

int main(int argc, char *argv[])
{
if(argc > 1) print_vertical(argv[1]);
return 0;
}
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
One last point: Early versions of C did not define the void keyword. Thus, in
early C programs, functions that did not return values simply defaulted to type int.
Therefore, don't be surprised to see many examples of this in older code.

Function :The General Form of a Function in C,C++

Functions are the building blocks of C and C++ and the place where all program
activity occurs. This chapter examines their C-like features, including passing
arguments, returning values, prototypes, and recursion. Part Two discusses
the C++-specific features of functions, such as function overloading and reference
parameters.


The General Form of a Function

The general form of a function is
ret-type function-name(parameter list)
{
body of the function
}
The ret-type specifies the type of data that the function returns.Afunction may return
any type of data except an array. The parameter list is a comma-separated list of variable
names and their associated types that receive the values of the arguments when the
function is called.Afunction may bewithout parameters, in which case the parameter
list is empty. However, even if there are no parameters, the parentheses are still required.
In variable declarations, you can declare many variables to be of a common type
by using a comma-separated list of variable names. In contrast, all function parameters
must be declared individually, each including both the type and name. That is, the
parameter declaration list for a function takes this general form:
f(type varname1, type varname2, . . . , type varnameN)
For example, here are correct and incorrect function parameter declarations:
f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */

Sunday, September 26, 2010

Multiple Indirection of Pointers C,C++

You can have a pointer point to another pointer that points to the target value. This
situation is called multiple indirection, or pointers to pointers. Pointers to pointers can
be confusing. Figure 5-3 helps clarify the concept of multiple indirection. As you can
see, the value of a normal pointer is the address of the object that contains the value
desired. In the case of a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the object that contains the value desired.
Multiple indirection can be carried on to whatever extent rquired, but more than a
pointer to a pointer is rarely needed. In fact, excessive indirection is difficult to follow
and prone to conceptual errors.
Do not confuse multiple indirection with high-level data structures, such as linked
lists, that use pointers. These are two fundamentally different concepts.
A variable that is a pointer to a pointer must be declared as such. You do this by
placing an additional asterisk in front of the variable name. For example, the following
declaration tells the compiler that newbalance is a pointer to a pointer of type float:
float **newbalance;
You should understand that newbalance is not a pointer to a floating-point number
but rather a pointer to a float pointer.
To access the target value indirectly pointed to by a pointer to a pointer, you must
apply the asterisk operator twice, as in this example:
#include <stdio.h>
int main(void)
{
int x, *p, **q;
x = 10;
p = &x;
q = &p;
printf("%d", **q); /* print the value of x */
return 0;
}
Here, p is declared as a pointer to an integer and q as a pointer to a pointer to an
integer. The call to printf() prints the number 10 on the screen.

Arrays of Pointers in C,C++

Pointers may be arrayed like any other data type. The declaration for an int pointer
array of size 10 is
int *x[10];
To assign the address of an integer variable called var to the third element of the
pointer array, write
x[2] = &var;
To find the value of var, write
*x[2]
If you want to pass an array of pointers into a function, you can use the same
method that you use to pass other arrays—simply call the function with the array name
without any indexes. For example, a function that can receive array x looks
like this:
void display_array(int *q[])
{
int t;
for(t=0; t<10; t++)
printf("%d ", *q[t]);
}
Remember, q is not a pointer to integers, but rather a pointer to an array of pointers to
integers. Therefore you need to declare the parameter q as an array of integer pointers,
as just shown. You cannot declare q simply as an integer pointer because that is not
what it is.
Pointer arrays are often used to hold pointers to strings. You can create a function
that outputs an error message given its code number, as shown here:
void syntax_error(int num)
{
static char *err[] = {
"Cannot Open File\n",
"Read Error\n",
"Write Error\n",
"Media Failure\n"
};
printf("%s", err[num]);
}
The array err holds pointers to each string. As you can see, printf() inside
syntax_error() is called with a character pointer that points to one of the
various error messages indexed by the error number passed to the function.
For example, if num is passed a 2, the message Write Error is displayed.
As a point of interest, note that the command line argument argv is an
array of character pointers. (See Chapter 6.)

Arrays of Strings in c c ++

It is not uncommon in programming to use an array of strings. For example, the input
processor to a database may verify user commands against an array of valid
commands. To create an array of null-terminated strings, use a two-dimensional
character array. The size of the left index determines the number of strings and the size
of the right index specifies the maximum length of each string. The following code
declares an array of 30 strings, each with a maximum length of 79 characters
char str_array[30][80];
It is easy to access an individual string: You simply specify only the left index. For
example, the following statement calls gets() with the third string in str_array.
gets(str_array[2]);
The preceding statement is functionally equivalent to
gets(&str_array[2][0]);
but the first of the two forms is much more common in professionally written
C/C++ code.
To better understand how string arrays work, study the following short program,
which uses a string array as the basis for a very simple text editor:
/* A very simple text editor. */
#include <stdio.h>
#define MAX 100
#define LEN 80
char text[MAX][LEN];
int main(void)
{
register int t, i, j;
printf("Enter an empty line to quit.\n");
for(t=0; t<MAX; t++) {
printf("%d: ", t);
gets(text[t]);
if(!*text[t]) break; /* quit on blank line */
}
for(i=0; i<t; i++) {
for(j=0; text[i][j]; j++) putchar(text[i][j]);
putchar('\n');
}
return 0;
}
This program inputs lines of text until a blank line is entered. Then it redisplays each
line one character at a time.