C++ Basics
Here is the general format for a C++ program:
File: program.cpp
/* Comments */
// More comments
#include <iostream>
#include <string>
… // Provides access to standard code libraries
#include "myclass.h" // Provides access to user-defined code
int g; // Global variables defined here
using namespace std; // Defines the namespace we’re using
// Define any functions here that are available globally, e.g.
void someFunc() {
// code
}
int main(char *argv[], int argc) // Parameters optional
{
// Code here for main returning an int value
}
Later on we will give the format to define classes. For now let’s see some basic innards
that make up a typical C++ program.
Primitive Data Types: Declaring variables with primitive data types is dust like Java and
C. There are some differences with scoping that we will discuss later when we discuss
classes and objects
Typical data types: char, int, long, float, double, bool (not boolean)
C++ treats 0 as false and non-zero as true
They behave the same as you would expect, just like in C or Java. This means
there are the same pitfalls. For example, if we divide integers:
double x = (2 / 3) * 6;
gives us 0 because we do integer division for 2/3 which results in 0 * 6.
We can also have roundoff errors to watch for. For example:
double d1 = 0.3;