Transitioning from C to C++: A Quick Guide for Novice Programmers

Transitioning from C to C++

Welcome to the world of C++! If you’re a novice programmer making the leap from C to C++, this guide is tailored just for you. Let’s dive into the key changes and features you’ll encounter as you explore the realm of C++.

As we begin the study of C++ and object oriented programming, a few comments are in order to help you get started. Since the field of object oriented programming is probably new to you, you will find that there is a significant amount of new terminology for you to grasp.

Table of Contents

Comments in C++

In C++, comments start with a double slash (//) and extend to the end of the line. The traditional ANSI-C comment notation (/* */) is still valid in C++. However, it’s recommended to use the double-slash method for better code readability and to avoid accidentally commenting out multiple lines.

// Example of comments in C++
#include <iostream>

void print_it(const int data_value);

int main() {
    const int START = 3; // The value of START cannot be changed
    const int STOP = 9; // The value of STOP cannot be changed
    volatile int CENTER = 6; /* The value of CENTER may be changed
    by something external to this
    program. */    int index; /* A normal C variable */    for (index = START ; index < STOP ; index++)
      print_it(index);
}

void print_it(const int data_value) {
    std::cout << "The value of the index is " << data_value << "\n";
}

The output of the program is:

  • The value of the index is 3
  • The value of the index is 4
  • The value of the index is 5
  • The value of the index is 6
  • The value of the index is 7
  • The value of the index is 8

The careful selection of variable and function names can make your C++ code self documenting and you should strive to achieve this in your code.

Keywords const and volatile

In C++, the const keyword is used to define constants. This keyword ensures that the values of constants cannot be changed. The compiler does not allow you to accidentally or purposefully change the value of START variable because it has been declared a constant. Similarly, the keyword const is used in the function header to indicate that the parameter named data_value is a constant throughout the function. Any attempt to assign a new value to this variable will result in a compile error.

The volatile keyword indicates that a variable may be modified by an external factor, such as a hardware function or an interrupt timer.

You can compile and execute this program with your C++ compiler to see if you get the same result as given in the comments at the end of the listing. One of the primary purposes of compiling it is to prove that your compiler is loaded and executing properly.

The Scope Operator

C++ introduces the scope operator (::) which allows you access to global variables even if a local variable shares the same name.

#include <iostream.h>

int index = 13;

int main()
{
  float index = 3.1415;

  cout << "The local index value is " << index << "\n";
  cout << "The global index value is " << ::index << "\n";

  ::index = index + 7; // 3 + 7 should result in 10

  cout << "The local index value is " << index << "\n";
  cout << "The global index value is " << ::index << "\n";
}

The output of the C++ Program is:

 The local index value is 3.1415
 The global index value is 13
 The local index value is 3.1415
 The global index value is 10

The scope operator allows access to global variables even though hidden by a local variable.

The iostream Library

C++ introduces the iostream library for flexible input and output operations. The cout and cin operators facilitate output to the console and input from the user.

#include <iostream>
#include <string>

main()
{
  int index;
  float distance;
  char letter;
  char name[25];
  index = -23;
  distance = 12.345;
  letter = 'X';
  strcpy(name,"John Doe");
  
  cout << "The value of index is " << index << "\n";
  cout << "The value of distance is " << distance << "\n";
  cout << "The value of letter is " << letter << "\n";
  cout << "The value of name is " << name << "\n";
  
  index = 31;
  cout << "The decimal value of index is " << dec << index << "\n";
  cout << "The octal value of index is " << oct << index << "\n";
  cout << "The hex value of index is " << hex << index << "\n";
  cout << "The character letter is " << (char)letter << "\n";
  
  cout << "Input a decimal value --> ";
  cin >> index;
  cout << "The hex value of the input is " << index << "\n";
}

The output of the C++ Program is:

 The value of index is -23
 The value of distance is 12.345
 The value of letter is X
 The value of name is John Doe
 The decimal value of index is 31
 The octal value of index is 37
 The hex value of index is 1f
 The character letter is X
 Input a decimal value --> 999
 The hex value of the input is 3e7

C++, like the C language itself, has no input or output operations as part of the language itself, but defines the stream library to add input and output functions in a very elegant manner.

The cout Operator: Precision in Output

The cout operator <<, sometimes called the “put to” operator but more properly called the insertion operator, tells the system to output the variable or constant following it, but lets the system decide how to output the data.

Because C++ has several other operators and functions available with streams, you have complete flexibility in the use of the stream output functions. You should refer to your compiler documentation for details of other available formatting commands. The cout and the printf() statements can be mixed in any way you desire.

The cin Operator: Reading Input in C++

In C++, the cin operator is your gateway to receiving input from the user via the standard input device, typically the keyboard. This operator employs the >> symbol, known as the “get from” operator but more accurately termed the extraction operator. It provides similar flexibility to the cout operator for output.

The cerr Operator: Error Output

In addition to cout and cin, there is another essential operator: cerr. This operator is specifically designed for error output and corresponds to the stderr stream pointer in C. Unlike cout, output through cerr cannot be redirected to a file.

#include <iostream>

int main() {
    // Example of using cerr for error output
    std::cerr << "An error occurred: Unable to open the specified file.\n";
}

File Stream Operations

We use the following C++ program demonstrates file stream operations. This program copies a file and prints its content. Let’s go through the code and understand its functionality:

#include <iostream>
#include <fstream>
#include <process.h>

using namespace std;

void main() {
    ifstream infile;
    ofstream outfile;
    ofstream printer;
    char filename[20];

    cout << "Enter the desired file to copy ----> ";
    cin >> filename;

    // Attempt to open the input file
    infile.open(filename, ios::_Nocreate);
    if (!infile) {
        cout << "Input file cannot be opened.\n";
        exit(1);
    }

    // Open output file for copying
    outfile.open("COPY");
    if (!outfile) {
        cout << "Output file cannot be opened.\n";
        exit(1);
    }

    // Open printer stream
    printer.open("PRN");
    if (!printer) {
        cout << "There is a problem with the printer.\n";
        exit(1);
    }

    cout << "All three files have been opened.\n";

    char one_char;

    // Start of the printed copy
    printer << "This is the beginning of the printed copy.\n\n";

    // Copy content from input file to output file and printer
    while (infile.get(one_char)) {
        outfile.put(one_char);
        printer.put(one_char);
    }

    // End of the printed copy
    printer << "\n\nThis is the end of the printed copy.\n";

    // Close all opened files
    infile.close();
    outfile.close();
    printer.close();
}

The output of the C++ Program is:

 (The input file is copied to the file named "COPY")
 (The input file is printed on the printer

The standard file I/O library is available with ANSI-C and is as easy to use as the stream library and very portable. For more information on the stream file I/O library refer to this article.

Variable Definitions

Automatic variables in C++ need explicit initialization. Reference variables and a more explicit for loop syntax are also introduced. Review the following C+ program for a few more additions to the C++ language which aid in writing a clear and easy to understand program.

#include <iostream.h>

int index;

int main()
{
  int stuff;
  int &another_stuff = stuff; // A synonym for stuff

  stuff = index + 14; //index was initialized to zero
  cout << "stuff has the value " << stuff << "\n";
  stuff = 17;
  cout << "another_stuff has the value " << another_stuff << "\n";

  int more_stuff = 13; //not automatically initialized
  cout << "more_stuff has the value " << more_stuff << "\n";

  for (int count = 3;count < 8;count++) {
    cout << "count has the value " << count << "\n";
    char count2 = count + 65;
    cout << "count2 has the value " << count2 << "\n";
  }

  static unsigned goofy; //automatically initialized to zero

  cout << "goofy has the value " << goofy << "\n";
}

Output of the C++ Program is:

 stuff has the value 14
 another_stuff has the value 17
 more_stuff has the value 13
 count has the value 3
 count2 has the value D
 count has the value 4
 count2 has the value E
 count has the value 5
 count2 has the value F
 count has the value 6
 count2 has the value G
 count has the value 7
 count2 has the value H
 goofy has the value 0

Automatic variables, those declared inside of any function, are not automatically initialized but will contain the value that happens to be in the location where they are defined, which must be considered a garbage value.

Reference Variable

C++ introduces reference variables using the ampersand (&) symbol. They act as synonyms for existing variables, providing an alternative way to access the same data. The reference variable is not quite the same as any other variable because it operates like a self dereferencing pointer. After initialization, the reference variable becomes a synonym for the variable, and changing the value of stuff variable will change the value of another_stuff because they are both actually referring to the same variable.

Declarations and Definitions in C++

In C++, “declaration” and “definition” have distinct meanings. A declaration provides information to the compiler about the characteristics of something (e.g., a type or a function). It does not actually define any code to be used in the executable program. A definition, on the other hand, actually defines something that will exist in the executable program, such as variables or executable code.

If we declare a struct, we are only declaring a pattern to tell the compiler how to store data later when we define one or more variables of that type. But when we define some variables of that type, we are actually declaring their names for use by the compiler, and defining a storage location to store the values of the variables. Therefore, when we define a variable, we are actually declaring it and defining it at the same time.

Variables and Scope:

Variables can be declared and defined near their point of usage in C++. This makes it easier to understand their purpose, as they have a more restricted scope. The scope of a variable is the region of the program where it is valid and accessible. Variables declared within a block (e.g., within a pair of curly braces {}) have a scope limited to that block.

For loop

The for loop in line 20 is highlighted as clearer than the one in ANSI-C. The loop index (count2) is declared within the loop itself, and its scope extends to the end of the enclosing block. This allows for better readability and avoids unintentional usage of the loop variable outside its intended scope.

Finally, as mentioned earlier, the static variable named goofy is declared and automatically initialized to zero in line 26. Its scope is from the point of its declaration to the end of the block in which it is declared, line 29.

Operator Reference

Operator reference in C++ encompasses both the well-defined operator precedence inherited from ANSI-C and the powerful concept of operator overloading. While initial familiarity with these topics is beneficial, a deeper understanding unfolds as you explore advanced scenarios and their practical applications in programming. The tutorial promises a gradual revelation of these intricacies, encouraging learners to embrace the journey of mastering C++ operators.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post