User Tools

Site Tools


opus:spring2012:smalik2:cprogpart3

cprog Keywords

17. Namespaces [C++]

Definition

Namespaces are basically ways to create global variables, but with a sort of 'subscope' type of feeling. Basically, let's say you have the variable of 'health'. You have the health of your character and the health of a creature. Well, you can't use the same health for both. This is where namespaces come in - we can define your health under the namespace 'Character' or something, and the health of the creature under the namespace of 'Creature'. To call health, you need to specify the namespace::health now - ensuring that there is no mix up with the different healths.

Demonstration

The above paragraph is a pretty good example, but I'm going to put down some super basic code just to get the syntax on here.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>                                                                                                                                             
 
namespace Character
{
    int health=100;
    int combat;
    long long int gold;
}
 
namespace Creature
{
    int health=25;
    int combat;
    long long int gold = 7;
}
 
int main()
{
 
    printf("Do you wish to enter combat with 'Creature'?\n\n0 for no\n1 for yes\n");
    scanf("%u", &Character::combat);
 
    if (Character::combat == 0)
    {   
        printf("Have a nice glory-free day.\n");
        return 0;
    }   
 
    do  
    {   
        if(Character::combat == 1)
        {   
            Creature::combat=1;
        }   
        else
        {   
            Creature::combat=0;
        }   
        Creature::health=25;
        while((Character::combat==1) && (Creature::combat==1))
        {   
            Character::health = Character::health - 3;
            Creature::health = Creature::health - 7;
 
            if (Creature::health <= 0)
            {   
                Character::gold = Creature::gold + Character::gold;
                printf("You killed 'Creature'.\nYou received %llu gold.\nYou have %u health remaining", Creature::gold, Character::health);
                printf("\nYou now have %llu gold\n", Character::gold);
                break;
            }   
 
            if (Character::health <= 0)
            {   
                printf("You have died.\n");
                return 0;
            }   
        }   
 
        printf("Do you wish to fight another creature? 0 for no 1 for yes\n");
        scanf("%u", &Character::combat);
    }   
    while(Character::combat==1);
    printf("You have fled from combat.\n");
 
    return 0;
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

lab46:~/src/cprog/messingaround$ ./Namespaces 
Do you wish to enter combat with 'Creature'?

0 for no
1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 88 health remaining
You now have 7 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 76 health remaining
You now have 14 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 64 health remaining
You now have 21 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 52 health remaining
You now have 28 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 40 health remaining
You now have 35 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 28 health remaining
You now have 42 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 16 health remaining
You now have 49 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You killed 'Creature'.
You received 7 gold.
You have 4 health remaining
You now have 56 gold
Do you wish to fight another creature? 0 for no 1 for yes
1
You have died.
lab46:~/src/cprog/messingaround$ 

18. Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments

Definition

Functions are basically blocks of code that are run when called, and can be given inputs (parameters). You can pass parameters by value (just give it the identifier), Address (using the & symbol), and by Reference (by pointers, for passing an array).

Functions can return values of different types, whether they be int, float, etc.

Recursion is when you call a function within a function, with a conditional break.

Demonstration

#include<stdio.h>                                                                                                                  
#include<stdlib.h>
 
int sum(int, int, int, int);    //function prototype
 
int main()
{
    int a,b,c,d;
    a=b=c=d=0;
 
    printf("\nEnter four numbers\n");
    scanf("%d%d%d%d", &a, &b, &c, &d);
 
    printf("The sum of %d, %d, %d, and %d is: %d\n", a,b,c,d, sum(a, b, c, d));
 
    return (0);
 
}
 
 
int sum(int a, int b, int c, int d)
{
    int SUM;
 
    SUM = a + b + c + d;
 
    return (SUM);
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

#include <stdlib.h>                                                                                                                
#include <stdio.h>
 
int main(int argc, char **argv)
{
    unsigned char i;
 
    if(argc < 2)
    {   
        printf("%8s must be run with 1 or \
        more arguments, you only provided %hhu\n", *(argv+0),(argc-1));
        exit(1);
    }   
 
    printf("You ran this program with %hhu arguments, they are:\n", argc);
 
    for(i=0; i<argc; i++)
    {   
        printf("argv[%hhu]: %s\n", i, *(argv+i));
    }   
 
    return(0);
 
}

19. Templates, STL (Standard Template Library) [C++]

Definition

Templates are kind of like function overloading. Except, you do the SAME THING given different parameters.

The STL is basically a library just filled with tons of templates to do stuff.

Demonstration

#include <stdlib.h>                                                                                                                  
#include <stdio.h>
#include <cstdio>
#include <iostream>
 
using namespace std;
 
template <class T>  //The T will basically be replaced by whatever 
T larger (T x, T y) //data type is necessary
{
    if (x >= y)
    {   
        return x;
    }   
    else
    {   
        return y;
    }   
}
 
int main()
{
    int a = 1200, b = 12; 
    float c = 3.1415, d = 143.24;
    char e = 65, f = 'B';
 
    cout << larger(a,b) << endl;
    cout << larger(c,d) << endl;
    cout << larger(e,f) << endl;
 
    return 0;
}
lab46:~/src/cprog/messingaround$ ./Template 
1200
143.24
B

20. Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]

Definition

Classes are wonderful little things good for organizing larger scale programs.

Objects are the things in the class, functions or variables or constants or friends, etc. Constructor is what runs when the class is being set up for usage. Optionary. Destructor is what runs when the class is deleted. Optionary. Access Control refers to the Public Protect and Private deal going on.

Public - Anybody can access this part. Protected - Only children can access this part (children are other classes that inherit from this class). Private - Only this class can access these parts. Friends - Allow you to rip through Access control, and access private parts from outside the class they belong to.

“This” pointer - When you make a new class to call and define it as a pointer, you have to use → to refer to it instead of a period.

Demonstration

There's two class-based programs in

cd /home/smalik2/src/cprog/c++

Also, Project 3.

21. Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)

Definition

The compiler takes your source code and translates it to assembly language.

The preprocessor deals with taking care of stuff before the actual compiling begins.

Flags are the command line arguments to the compiler, such as -02.

Assembler takes the assembly code (step 1 of compiling) and converts it into true machine code.

The Linker takes care of making sure that stuff from other libraries and header files and stuff will work correctly and be there.

Multi-file programs are programs made over multiple files.

Demonstration

I'll compile a multi-file program here.

lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.h  shape.cc  shape.h  square.cc  square.h  triangle.cc  triangle.h
lab46:~/src/cprog/c++/today$ g++ -c *.cc
lab46:~/src/cprog/c++/today$ ls
main.cc  rectangle.cc  rectangle.o  shape.h  square.cc  square.o     triangle.h
main.o   rectangle.h   shape.cc     shape.o  square.h   triangle.cc  triangle.o
lab46:~/src/cprog/c++/today$ g++ -o Program *.o
lab46:~/src/cprog/c++/today$ ./Program 
1 for Rectangle
2 for Square
3 for Triangle
2
You chose square. Enter the width/length: 12

The perimeter is: 48
The area is: 144

Einen schönen Tag noch, Ruck.

lab46:~/src/cprog/c++/today$ 

22. Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]

Definition

Type Casting is basically converting some type of data into another type. Const is a keyword that means that the type can not be changed. Volatile is a keyword that means you can modify using some tricks.

Demonstration

We didn't really go into this in class, except for when we used arrays.

When we used malloc to create an array, we were type casting it so that the memory we gave to the array would behave properly - according to the data type that we wanted for the array.

float *Array;
Array = (float*)malloc(sizeof(float)*50);      //(float*) is a type cast.

23. typedef, enum, union

Definition

A typedef basically let's you take something, and create a shortcut for it. This shortcut now represents what you originally typedef, and the two can be used interchangeably. An enum is a data type that consists of named values. A union is kind of like a struct, where it holds a bunch of different types of data. The trick is, you can only have one type of data in it at a given time. Assigning new data, overwrites the old data.

Demonstration

There's a typedef in the EoCE. There's an enum and union in my cprog folder.

24. Structures (Declaration, Accessing Elements, Pointers to)

Definition

Structures are basically The C version of classes. They are heterogeneous data types, and can hold multiple things. Functions and data types. They are really good and useful for organization oriented stuff.

Demonstration

On the EoCE there is a lot of strcuture stuff on 0x6 and 0x7.

cprog Objective

cprog Objective

justify the use of various programming constructs within code solutions

Definition

This objective means being able to build a solution for a problem using some sensible approach. On top of that, you outta be able to come up with very sound reasons for your approach. (Why did I use classes to do this? For example).

Method

I can judge how well I organize my code, and whether or not my methods make sense/ are good.

Measurement

I normally take a very good approach in how I organize and construct my solutions to problems, so I figure I do a pretty decent job of it.

Analysis

  • How did you do? I think I did well.
  • Is there room for improvement? Of course there is!
  • Could the measurement process be enhanced to be more effective? I don't know - perhaps using an outside source. If somebody else can tell why I took an approach that's even better.
  • Do you think this enhancement would be efficient to employ? If people agreed to help me.
  • Could the course objective be altered to be more applicable? How would you alter it? Not particularly, I wouldn't alter it.
opus/spring2012/smalik2/cprogpart3.txt · Last modified: 2012/05/09 16:06 by smalik2