Showing posts with label functions. Show all posts
Showing posts with label functions. Show all posts

Thursday, 5 April 2012

Passing An Array to Functions in C & C++


The previous entry looked at various ways to pass a variable to a function: by value, by reference or by pointer. This entry looks at passing an array to a function. In C/C++ arrays are passed by reference or by pointer, not by value. This means the called function can directly change the array as passed by the caller. You can however pass one element of an array by value in the same way you pass an integer or other data type.

The sample code calls a function, CapFirstLetter, which takes a character array from the caller and raises the first letter of each word to uppercase.

The character array is created by:

     char Text[] = "Some words to cap.";

I can then define the function signature in one of two ways: with or without a pointer.

int CapFirstLetter(char vText[]);
int CapFirstLetter(char * vText);

The code inside the function is the same.

I can then call the function in one of three ways:

CapFirstLetter(Text);

CapFirstLetter(&Text[0]);

char * pText = &Text[0];
OR
char * pText = Text;
CapFirstLetter(pText);

The critical point to remember is that using the name of the array, in this case, Text, is actually a pointer to the first element of the array. Thus, using Text is the same as using &Text[0] and a pointer can be assigned using either method. The result is the same.

Sample Code.

// Standard I/O library.
#include <cstdio>

// Prototypes.
int CapFirstLetter(char vText[]);
int CapFirstLetter2(char * vText);

int main()
{

     printf("Call Function To Cap First Letter of Every Word\n\n");

     /////////////////////////////////////////////////////////////////
     // 1. Pass array by array name.

     printf("1. Pass array by array name.\n\n");
     char Text[] = "Some words to cap.";
     CapFirstLetter(Text);
     printf("Version 1: %s\n", Text);
    
     // The name of the array is a pointer to first element.
     char Text2[] = " This   function   handles extra spaces.";
     CapFirstLetter(&Text2[0]);
     printf("Version 2: %s\n\n\n", Text2);

     /////////////////////////////////////////////////////////////////
     // 2. Pass array by pointer variable.

     printf("2. Pass array by pointer variable.\n\n");
     // Create pointer.
     char Text3[] = "a statement with all lowercase letters";

     // Option 1.
     // The name of the array, Text3, is a pointer to Text3[0].
     // char * pText = Text3;

     // Option 2.
     // Another way to get the address of the first element.
     char * pText = &Text3[0];
     CapFirstLetter(pText);
     printf("Version 3: %s\n", Text3);
    
     // Start later in the array.
     char Text4[] = "a statement with all lowercase letters";
     pText = &Text4[2];
     CapFirstLetter(pText);
     printf("Version 4: %s\n", Text4);

     // Close the file.
     fclose(stdout);

     // Return something.
     return 0;
}
int CapFirstLetter(char vText[])
{
     /////////////////////////////////////////////////////////////////
     // Capitalize first letter of a string of text.

     short i;
     bool PrevSpace = true;

     for (i = 0; vText[i]; i++)
     {
           // Look to find start of new word.
           if (PrevSpace)
           {
                // Ignore space.
                if (vText[i] == ' ')
                     // Go to next char.
                     continue;
                // Not a space, reset flag.
                PrevSpace = false;
                // Want lowercase only.
                if ((vText[i] >= 97) && (vText[i] <= 122))
                {
                     // Appy uppercase.
                     vText[i] -= 32;
                }
           }
           else
           {
                // Start of new word.
                if (vText[i] == ' ')
                     // Reset.
                     PrevSpace = true;
           }
     }

     // Return success.
     return 0;
}

Output.


Wednesday, 4 April 2012

Passing Data to Functions in C & C++


C and C++ are built on functions. All programs in C/C++ start with a main() function and branch out from there to other functions. Generally, since it's considered poor coding practice to use global variables, you will need a way to pass local variables from one function to another. This blog looks at the different way of passing data to a function.

1. Pass By Value.

The default in C/C++ is to pass the value of a variable to a function. This means the function cannot change the value of the variable in the caller function. Here is some test code to show this point.

int i = 10;
printf("Pass Argument by Value.\n");
printf("Value before function call: %d.\n", i);
ByVal(i);
printf("Value after function call: %d.\n", i);

void ByVal(int Parameter)
{
     // Change won't happen.
     Parameter = 100;
     printf("Value in function: %d.\n", Parameter);
}

>Pass Argument by Value.
>Value before function call: 10.
>Value in function: 100.
>Value after function call: 10.
 
When a variable is passed to a function by value, the language copies the value to the heap—the dynamic runtime memory. The variable in the caller function is thus duplicated—one copy in the caller function and one copy for the called function. This is not an efficient use of resources. It uses up memory and it takes time to copy the data. A better way is to pass a memory address of the variable to the called function.

2. Pass By Reference.

If I declare MyVar as integer type, I can find out its memory address with the & operator. The first method of passing a memory address to a variable uses this operator. I define the function with a parameter of DataType &VariableName.

i = 20;
printf("\nPass Argument by Reference.\n");
printf("Value before function call: %d.\n", i);
printf("Address of i in main: %#X.\n", &i);
ByRef(i);
printf("Value after function call: %d.\n", i);


void ByRef(int &Parameter)
{
     // Value changes.
     Parameter = 200;
     printf("Value in function: %d.\n", Parameter);
     printf("Address of Parameter in function: %#X.\n", &Parameter);
}


>Pass Argument by Reference.
>Value before function call: 20.
>Address of i in main: 0X36EB8C.
>Value in fn: 200.
>Address of Parameter in function: 0X36EB8C.
>Value after function call: 200.

Because the function ByRef function has direct reference to the i variable, it can change the value. You will note the memory address is the same inside the function as it is in the caller function.

3. Pass By Pointer.

The previous example indirectly passed the memory address for the parameter with ByRef(i) instead of ByRef(&i). The function used the & operator. In this example, the caller must pass a pointer—a direct reference to the memory location. The end result is the same.

int* pi = &i;
i = 30;
printf("\nPass Argument by Pointer.\n");
printf("Value before function call: %d.\n", i);
printf("Address of i in main: %#X.\n", pi);
ByPointer(pi);
printf("Value after function call: %d.\n", *pi);

void ByPointer(int* Parameter)
{
     // Value changes.
     *Parameter = 300;
     printf("Value in function: %d.\n", *Parameter);
     printf("Address of Parameter in function: %#X.\n", Parameter);
}

>Pass Argument by Pointer.
>Value before function call: 30.
>Address of i in main: 0X36EB8C.
>Value in fn: 300.
>Address of Parameter in function: 0X36EB8C.
>Value after function call: 300.
 
Calling the function with a pointer, ByPointer(pi), is equivalent to this: ByPointer(&i).

These examples used the integer data type. The code could be modified to use the other built-in data types: char, bool, double, float. For passing an array, especially a character array, to a function, see the next blog entry.

Friday, 2 March 2012

A Function In A Function In C & C++


C is all about functions. Right? Well, it’s structured around functions. A program written in C always starts with a function called main and then calls various functions along the way. Some of the functions are part of the standard library and some are user defined. I wanted to know if you could write a function within a function. It happens all the time in other languages. Why not C?

I started with a bare bones main function.

int main()
{
     // return some value
     return 0;

} // end main

That code works. It compiles. It runs. But nothing happens.

I then added a function fn() inside this main function.

int main()
{
     // Prototype declaration.
     int fn();

     // return some value
     return 0;

     int fn()
     {

          return 0;
     }


} // end main

It wouldn’t compile. I got this compile error:

error C2601: 'fn' : local function definitions are illegal

End of that story. You can’t define a function inside of another function in C. Not sure why. I expect there is some sort of explanation. Must be. But for now, C is a series of functions, all separate, one after another with the focus on the main function.