C++ Language Basics Part I (2024)

(I/O, functions, keywords, structures, memory alloc, commenting)

The C++ programming language can be thought of as a ``superset''of the C language; that is, just about any legal Ansi C programis a legal C++ program, and means the samething. The reverse is not true of course: there are many C++ constructsthat are not found in the C programming language. This handoutdescribes some of those constructs that we will be using in this class.

Input and Output

In C, input and output is traditionally doneusing the functions printf and scanf(along with getchar()).When reading from files, the routines fprintfand fscanf are used. Unfortunately, it's prettyeasy to crash a program using these functions.For example,

int d = 3;char *str = "hi there!";printf("d is %d, and str is %s\n", str, d);

will probably cause your program to crash, because the programmer mixedup the arguments to printf. The routine scanfis even worse: for example,

double d;float f;int i;scanf("%d", i); /* wrong, should be &i */scanf("%f", &d); /* wrong, needed to specify %lf */scanf("%f", &f); /* this one is OK */

The major problem is that you can usually only find these bugsat run-time. However, it would be much better for the compilerto be able to look at the statement scanf("%d", i) anddetermine that a pointer to an integer, not simply an integer,was required here. While you can't do that with C styleoperators (since the correct arguments to printfand scanf vary, depending on the formatting string),in C++ there are routines that will eliminate mostof these bugs.

Let's look at an example:

#include <iostream.h>main() { int a, b; double d; char str[20]; cin >> a; // equivalent to scanf("%d", &a); cin >> b; // equivalent to scanf("%d", &b); cin >> d; // equivalent to scanf("%lf", &d); cin >> str; // equivalent to scanf("%s", str); cout << "The sum of a and b is"; cout << a + b; cout << "\n";}

First, the file iostream.h is a standard C++ headerfile that defines cin, cout, and theoperators << and >>. The expressioncin >> a causes the program to read an integer intothe variable a, from the standard input. Similarly,cin >> b reads an integer into b,but cin >> d interprets its input as a real number, andstores it in d. The next statement, cin >> strreads characters until a whitespace is encountered, andstores a null-terminated string in str (excludingthe whitespace). Note that if you typed a very longstring (i.e. more than 20 characters), your program could crash.

Output is much the same: with the expression cout << thing,the contents of thing is printed to the standardoutput. Note a couple of subtleties:

int ival = 'g'; // The ASCII code for g is 103, so ival = 'g'char cval = 'g'; // is equivalent to ival = 103.cout << ival; // treats ival as a number, and prints out 103cout << cval; // prints out simply the letter g

A few other things: You can combine any number of outputor input operations in a row e.g.

cin >> a >> b >> d >> str;
is fine, and is equivalent to the four seperate lines above.Similarly, statements like
cout << "The sum of a and b is " << a+b << "\n";
are permissible as well. (Note the space after the word ``is.''Without extra space, i.e.,
int x = 23;cout << "The value of x is" << x << "\n";

you get

The value of x is23

You can test when you've run out of input:

int x;while(cin >> x) { ...}

will loop until there is no more input, or untilan invalid string is entered (e.g. ``hi,'' which is not a validinteger).

It is also possible to make the << and >>output operators know how to output user-defined types:for example, if you create new datatypes, you canteach the << and >> operators how to inputand output directly from those datatypes. (See the C++ book,or ask the teaching staff how this works, if you're interested).

If you want to do I/O to a file (i.e. the equivalentof fprintf), you can get declare variables like coutthat are used just as cout is, but that cause the outputto go to a particular file. You can do input from a filesimilarly. There is an example of this in Assignment 1. If you wantto know more details, consult the C++book, or the teaching staff.

Finally, in addition to sending output to cout, youcan also send output to the ``standard error'' byusing cerr e.g.

if(i < 0) { cerr << "Fatal error: i is less than zero!\n"; exit(1);}

This is analogous to using fprintf to stderr.

Function Declarations

In C++ it is illegal to use a function without first declaring itstype. In C, if you don't declare a function's type, certaindefaults apply. This is not the case with C++. You mustdefine a function before you can use it.

Additional Keywords

Every keyword, or reserved-word in C is also a keyword in C++.There are extra keywords in C++ that have no meaningin C. Since C++ is becoming prevalent, even when programmingin C you should avoid the use of all of the followingC++ keywords as function or variable names. In C++ you cannotuse any of the following words as function or variable names:

asm delete if return tryauto do inline short typedefbreak double int signed unioncase else long sizeof unsignedcatch enum new static virtualchar extern operator struct voidclass float private switch volatileconst for protected template whilecontinue friend public thisdefault goto register throw

Defining Structures

In C++, when you define a structure, the name of the structureis henceforth treated as a new datatype. For example:

struct complex { double x, y;};complex a, b, c;

Also, note the semicolon at the end of the definitionof the complex structure: this semicolon is required.After defining the structure, you can use complexas a datatype. Its still legal to say

struct complex a, b, c;
if you want to. The above discussion applies to unions as well.

Memory Allocation

In C, we allocate space using malloc. For example,

double *dspace = (double *)malloc(sizeof(double) * 10);
dynamically allocates space for 10 doubles. In C++, we usethe construct new:
double *dspace = new double[10];
To allocate space for the complex structure defined above,the syntax is simply
complex *cptr = new complex[37];

To return memory in C, we use free:

In C++, memory is returned by
delete dspace; /* or, delete []dspace; */
delete cptr; /* or, delete []cptr; */

The format with square brackets is needed when you have an array ofitems each having its own destructor (we'll talk about destructorslater on in the course).As in C, though, if you try to write past the end of the memoryallocated by new, your program will probably not work correctly.Incidentally, the delete operator is guaranteed to haveno effect when applied to a pointer whose value is zero (NULL).Handing delete a pointer that was not returned by newis a bad idea. To more easily catch cases when you've deletedmemory but later tried to use it, the code

delete dspace;dspace = 0;

is recommended, since the use of dspace after the deletionwill be easier to detect.

Overloading of Functions

In C, a name can only be used once to define a function.For example, in C, the following is illegal:

double minimum(double x, double y){ if(x < y) return x; else return y;}int minimum(int x, int y){ if(x < y) return x; else return y;}

This is perfectly legal C++ code, however, and is knownas an overloaded function. If you call minimumin your code, the compiler will decide which version of minimumto invoke based on the types of the arguments you supply to the function.Appropriate uses for overloading are reusing mathematicalfunction names for operations on different data; for example,two versions of sqrt: one for real numbers, and onefor complex numbers. Another typical use might be a function namednode_count which returns the number of nodes in differingdata structures such as linked lists, trees, or graphs.You will probably have little use for operator overloadingin this class.

The reason we bring up the subject at all, is to make you awareof the following pitfall. Suppose that you declare in a headerfile defs.h a function foo as follows:

/* file defs.h */int foo(double, int, char);

Now suppose that you wish to use the function fooin a file a.c:

/* file a.c */#include "defs.h"void do_something(){ int result; result = foo(3.4, 7, 'c');}

Ok, no problems so far: the file a.c correctlyincludes defs.h so it can access the function foo.Suppose, though, you made a mistake in the file b.c, wherefoo is actually defined:

/* file b.c */#include "defs.h"/* Here's my great implementation of foo: by juxtaposing the seventh and ninth bit from the third argument, I cleverly manage to ...*/int foo(double a, int b, int c){ ...}

The problem is that the C++ compiler thinks you're defininga function foo which takes a double and two integers.This is perfectly legal. The problem comes when you actuallycompile and try to run everything. At that point, the function namedfoo that takes a double, an integer, and a character,will be undefined, because in b.c you defined a differentfunction foo.

Moral of the story: if you get undefined function errorsfrom the compiler, make certain that you defined your functionwith the types you really meant to.


C++ allows two types of comments. In addition tothe standard ``/*'' and ``*/'' comments of C,there is a special comment which is good only to the end of a line.In C++, characters occuring after the sequence ``//''and on the same line are ignored, as long as the ``//''does not occur in a string. For example:

/* If low is greater than high, interchange the values and set 'swapped' to 1.*/if(low > high){ tmp = low; // save low low = high; high = tmp; // now swap swapped = 1; // indicate we swapped the data}

One thing to be VERY careful of is not to use C++ style commentsin #define statements, because most compiler systems don'tmix the two together correctly.That is, for now (and probably forat least another 10 years!) don't write

#define MAX_LEN 128 // maximum length string

but use

#define MAX_LEN 128 /* maximum length string */


C++ Language Basics Part I (2024)
Top Articles
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated:

Views: 5888

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.