Fundamentals (part 1)

Introduction

C++ is built upon and extends the C programming language

Most of the C++ extensions provide efficient object-oriented capabilities

Since C++ is built from C, C++ programs can include C language features

Many C language features are beneficial to use in C++ programs

Due to its widespread use, many programs have been and still are written in C

C++ programmers should be well-versed in the fundamentals of the C language

We will be looking at many C concepts throughout the course

Consider the following simple C program below

#include <stdio.h>

 

int add( int );

 

int main()

{

  int val, retVal;

 

  val = 10;

  retVal = add(10);

  printf( "Value = %d\n", retVal );

 

  return 0;

}

 

int add( int a )

{

  return a+10;

}

 

main Function

Note that C (and C++) programs begin with a main function

This is a single function defined within a global scope

Syntactically, this is quite different than a simple “Hello world” Java program

public class FirstProgram

{

      public static void main( String [] args )

{

            System.out.println( “Hello world” );

}

}

Notice that main is inside a class in Java

Java can have multiple mains in different classes

As a function, main returns control to the operating system (OS) after execution

Although not required, main returns an integer type back to the OS

int main()

{

  ..

 

  return 0;

}

 

 

 

Compiling

C/C++ programs are not interpreted as with Java programs

Different from Java, C/C++ programs are compiled directly to native machine code

Not necessary to generate bytecode (javac), then interpreted code (java) as in Java

We will be using the GNU compiler (g++) under Unix to compile our C/C++ programs

To experiment, enter the example code above using Emacs and save the file as example1.cpp

To compile, simply invoke the GNU C/C++ compiler from the command line:

dbock@shaula % g++ example1.cpp

 

Run the executable output (named a.out by default) from the command line:

dbock@shaula % a.out

 

 

Functions

Recall that functions provide a convenient method of encapsulating tasks

Well-written, useful functions provide for great reusability by other programs

We can even group related functions into reusable libraries

Let’s look at the structure of a function in the C/C++ programming language

Function definition

 

return-type functionName( parameter declarations )
{
    body of function...
}

return-type
    - The variable type to be returned by the function to the calling program
    - If the return type is omitted, type int is assumed
    - main is a function, int return type, returns to calling environment
    - return statement used to return the declared type
 

parameter declarations
    - Defines and declares the arguments passed to the function
    - The actual name of the argument is known as the formal parameter name
    - The term argument refers to the actual value of the parameter
    - The function uses the parameters/arguments to perform some task

Let’s look closely (in red) at our example code above

#include <stdio.h>

 

int add( int );

 

int main()

{

  int val, retVal;

 

  val = 10;

  retVal = add(10);

  printf( "Value = %d\n", retVal );

 

  return 0;

}

 

int add( int a )

{

  return a+10;

}

Note that C/C++ functions can exist on their own outside of a class

The function add is first declared globally outside of main

int add( int );

This lets the compiler know that add is a function with a specific parameter type (int) and return type (int)

This statement “declares” to the compiler this user-defined function that is used in main

Hence, this statement is called a function declaration (declares the function to the compiler)

The function declaration is sometimes referred to as the function prototype

The code below main contains the actual statements that are contained in the function

int add( int a )

{

  return a+10;

}

These statements define the function (or actual instructions) to the compiler

Hence, these statements are referred to as the function definition

Be sure you know the difference between a function declaration and definition

Finally, the function is executed or called by main with the statement

retVal = add(10);

The value passed to the function is added and returned to the calling program (main)

Looking again at the example, we notice another function statement in main

printf( "Value = %d\n", retVal );

This is also a function that is being called by main to print information to standard out

This is referred to as a system function (its definition is in a pre-compiled system library)

System libraries are collections of pre-compiled system functions

Like other functions, this function needs to be declared before main

The function declaration for the printf function is in the file stdio.h included in main

The purpose of this function is to print output information for the user

 

C/C++ I/O

In our example above, we are calling a C function to print information to standard out

printf( "Value = %d\n", retVal );

This standard system library function can be used to print in a variety of ways

Similar system functions can be used to input data into programs (scanf)

#include <stdio.h>

 

int main ()

{

  char str [80];

  int i;

 

  printf ("Enter your surname: ");

  scanf ("%s",str); 

  printf ("Enter your age: ");

  scanf ("%d",&i);

  printf ("Mr. %s , %d years old.\n",str,i);

  printf ("Enter a hexadecimal number: ");

  scanf ("%x",&i);

  printf ("You have entered %#x (%d).\n",i,i);

 

  return 0;

}

System functions also provide I/O functionality for disk files (fprintf, fscanf)

A plethora of manuals exist that describe standard C I/O in detail, here is a good one

Be sure to study and become well-versed with the C I/O functions for use in assignments

A different method of I/O was added in C++ to facilitate I/O streaming

We’ll be studying C++ I/O in detail later, but for now consider the following example

#include <iostream>

using namespace std;

 

int main()

{

  cout << "Hello World" << endl;

  return 0;

}

The first two lines instruct the compiler to include and use specific C++ information

The output statement

  cout << "Hello World" << endl;

is the C++ output mechanism to send information (and a newline) to standard out

Another form of the same program that is used in the textbook is:

#include <iostream>

 

int main()

{

  std::cout << "Hello World" << endl;

  return 0;

}

Both forms work the same way and differ by how the information is specified

Again, more to come on this topic when we look closely at C++ I/O streams

Both the C and C++ input/output methods can be used in C++ programs

 

Function Parameters

In our original example, a parameter was passed to a function in order to perform a task

retVal = add(10);

Let's look a bit more closely at what is actually going on when we pass parameters

When a function is called with parameters...

Temporary memory space is setup to hold each parameter (size indicated by type)

This temporary space in memory is called the stack

The actual values of the parameters are then copied into this temporary space

The function then uses these copies to operate on within its body

The original parameter values remain "untouched" in their original memory space

In this way, the function is given the values of the parameters in temporary variables, not the original variables

Hence, the function cannot alter a variable from the calling function, only its own temporary copy

This method of passing arguments is also termed "call by value"

We can visualize this process with memory represented as rectangular blocks below

Each block has an address (let’s use 1000, 1001, 1002, …) to designate its location

In the diagram below, the value for the variable is stored in memory at location 1001

Memory is setup (allocated) on the stack at location 3000 to store a copy of the parameter

This value is changed while the original variable in main is untouched

 
Question

If a function alters (or changes the value) of its temporary copy of a parameter variable, will it affect the variable contents within the calling program?


Example

void addTo( int, int );

main()
{
    int ivalue = 10;

    printf( "ivalue before function is called: %d\n", ivalue );

    addTo( ivalue, 10 );

    printf( "ivalue after function is called: %d\n", ivalue );
}

void addTo( int value, int x )
{
    value += x;
}

Output
ivalue before function is called: 10
ivalue after function is called: 10

 

Answer

No, the value of the variable in main never changed!

Question

What if we wanted to change the parameter variable contents in the calling program from within the function?

Answer

Fundamentals, part II