CS 2150 Roadmap

Data Representation

Program Representation

 
 
string
 
 
 
int x[3]
 
 
 
char x
 
 
 
0x9cd0f0ad
 
 
 
01101011
vertical red double arrow  
Objects
 
Arrays
 
Primitive types
 
Addresses
 
bits
           
 
Java code
 
 
C++ code
 
 
C code
 
 
x86 code
 
 
IBCM
 
 
hexadecimal
vertical green double arrow  
High-level language
 
Low-level language
 
Assembly language
 
Machine code

using Directive

 

  • Similar to Java's import
    • Uses a namespace, which is somewhat similar to a Java package
    • Allows the programmer to not have to type the full namespace name each time
 
// C++
#include <iostream>
using namespace std;
int main() {
    cout << "Hello World!" 
         << endl;
    return 0;
}
// C++
#include <iostream>
int main() {
    std::cout << "Hello World!" 
              << std::endl;
    return 0;
}

Error comparison

 

g++:g++ error message
clang++:clang++ error message

Declaring mutually
recursive functions

Source code: evenodd.cpp (src)

   
bool even (int x);
bool odd (int x) {
    if ( x == 0 )
        return false;
    else
        return even (x-1);
}
	  

 

bool even (int x) {
    if ( x == 0 )
        return true;
    else
      return odd (x-1);
}
	  

Pointer Variables

Source code: pointers.cpp (src)

VariableAddressMemory

x

1000

1

y

1008

5

x_pointer

1016

1000

1024

 

1032

 

int x = 1;
int y = 5;
int * x_pointer = &x;
cout << x_pointer;
cout << *x_pointer;

x_pointer = &x

Poitner code execution

*x_pointer = 2

Poitner code execution

x_pointer = &y

Poitner code execution

*x_pointer = 3

Poitner code execution

Pointer Pitfalls: Uninitialized Pointers

  • Cause runtime errors
    int n = 30;
    int * p;
    *p = n;    //ERROR!!!
    
    • p does not have a valid memory address!
    • A common initializer value used by programmers is NULL
      int *p=NULL; // better code, then add code to check 
                   // for NULL value
      

swap()

Source code: swap.cpp (src)

void swap(int * x, int * y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}