C++ Enum

C++ Enum

Quando si definisce una variabile di tipo enumerativo, ad essa viene associato un insieme di costanti intere chiamato insieme dell’enumerazione. La variabile può contenere una qualsiasi delle costanti definite.

enum


// Sintassi
enum type_name {
  value1,
  value2,
  value3,
  .
  .
} object_names;


// 1. definiamo secchio come un tipo di dati enum
// all'interno indico il valore delle costanti
enum secchio {
    VUOTO,
    MEZZO_PIENO,
    PIENO = 5
} mio_secchio;

// 2. poi possiamo definire:
secchio tuo_secchio;
// oppure in modo equivalente
enum secchio tuo_secchio;

// 3. poi posso assegnare i valori delle costanti
// NON POSSO ASSEGNARE VALORI AL DI FUORI DELLE COSTANTI
mio_secchio = PIENO;
tuo_secchio = VUOTO;

Un’altro esempio:
creo un tipo di variabile colors_t dove immagazzinare i colori.

...
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};
...

enum class

Con ‘enum class’ possiamo dichiarare non solo interi, ma anche altri tipi di dato.

...
enum class EyeColor : char {blue, green, brown}; 
...

My Website: http://www.lucedigitale.com

Reference: http://www.cplusplus.com/doc/tutorial/other_data_types/
Reference: http://www.html.it/pag/15478/gli-identificatori/

By |C++, Video Games Development|Commenti disabilitati su C++ Enum

C++ Unions

C++ Unions

Unions allow one portion of memory to be accessed as different data types.

The code below creates a new union type, identified by type_name, in which all its member elements occupy the same physical space in memory. The size of this type is the one of the largest member element.


// Syntax
union type_name {
  member_type1 member_name1;
  member_type2 member_name2;
  member_type3 member_name3;
  .
  .
} object_names;

// The Sample code...
union mytypes_t {
  char c;
  int i;
  float f;
} mytypes;

// ...declares an object (mytypes) with three members
mytypes.c
mytypes.i
mytypes.f	

For italian people: la peculiarità della union è che tutte le sue variabili membro (in questo caso l’intero non segnato intero e l’array di char caratteri) condividono la stessa area di memoria, a partire dallo stesso indirizzo: in altri termini intero e caratteri occupano gli stessi 4 byte in memoria.
Tale proprietà si rivela molto utile, ad esempio, nella gestione dei colori in un ambiente grafico come X11. In un simile contesto, una union come quella del presente esempio consente di accedere “istantaneamente” alle componenti alpha, rossa, verde e blu del colore di un pixel senza ricorrere ad alcuna operazione di “bit masking” o “scorrimento bit”.

By |C++, Video Games Development|Commenti disabilitati su C++ Unions

C++ typedef

C++ typedef

A type alias is a different name by which a type can be identified. In C++, any valid type can be aliased so that it can be referred to with a different identifier.

For italian people: lo scopo della typedef è quello di assegnare dei nomi alternativi a dei tipi di dato esistenti, solitamente a quelli la cui dichiarazione standard è troppo ingombrante, magari confusionale, oppure per rendere il codice riutilizzabile più facilmente tra un’implementazione e un’altra.

Without typedf:

int current_speed ;
int high_score ;
...
 
void congratulate(int your_score) {
    if (your_score > high_score)
...

With typedef:

typedef int km_per_hour ;
typedef int points ;
 
km_per_hour current_speed ;
points high_score ;
...
 
void congratulate(points your_score) {
    if (your_score > high_score)
...

Entrambe le sezioni di codice implementano la stessa operazione. Ciononostante, l’uso della typedef nel secondo esempio rende più chiaro il fatto che, nonostante le due variabili sono rappresentate dallo stesso tipo di dato (int), le informazioni in esse contenute sono logicamente incompatibili.

My website: http://www.lucedigitale.com

Reference: http://it.wikipedia.org/wiki/Typedef

By |C++, Video Games Development|Commenti disabilitati su C++ typedef

C++ Data Structures – Arrow Operator

C++ Data Structures – Arrow Operator

A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.

Regular Variables

The syntax is:


// syntax
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

// working sample:
struct product {
  int weight;
  double price;
} apple, banana, melon;

// access
apple.weight
apple.price
banana.weight
banana.price
melon.weight
melon.price

Working sample:


// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// declare data structure
struct movies_t {
  string title;
  int year;
} mine, yours;

void printmovie (movies_t movie);

int main ()
{
  string mystr;

  mine.title = "2001 A Space Odyssey";
  mine.year = 1968;

  cout << "Enter title: ";
  getline (cin,yours.title); // store title
  cout << "Enter year: ";
  getline (cin,mystr);
  stringstream(mystr) >> yours.year; // store year

  cout << "My favorite movie is:\n ";
  printmovie (mine);
  cout << "And yours is:\n ";
  printmovie (yours);
  return 0;
}

void printmovie (movies_t movie)
{
  // access data structure
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

The result is:
Enter title: Alien
Enter year: 1979

My favorite movie is:
2001 A Space Odyssey (1968)
And yours is:
Alien (1979)

Arrays

You can use an Array into Data Structures:


// array of structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
} films [3];

void printmovie (movies_t movie);

int main ()
{
  string mystr;
  int n;

  for (n=0; n<3; n++)
  {
    cout << "Enter title: ";
    getline (cin,films[n].title);
    cout << "Enter year: ";
    getline (cin,mystr);
    stringstream(mystr) >> films[n].year;
  }

  cout << "\nYou have entered these movies:\n";
  for (n=0; n<3; n++)
    printmovie (films[n]);
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

The result is:
Enter title: Blade Runner
Enter year: 1982
Enter title: The Matrix
Enter year: 1999
Enter title: Taxi Driver
Enter year: 1976

You have entered these movies:
Blade Runner (1982)
The Matrix (1999)
Taxi Driver (1976)

Pointers to Data Structures


// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
};

int main ()
{
  string mystr;

  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;

  cout << "Enter title: ";
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;

  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";

  return 0;
}

The result is:
Enter title: Invasion of the body snatchers
Enter year: 1978

You have entered:
Invasion of the body snatchers (1978)

Arrow Operator

The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members. This operator serves to access the member of an object directly from its address.


// arrow operator
pmovie->title
// equivalent to:
(*pmovie).title

Working example:


// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
};

int main ()
{
  string mystr;

  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;

  cout << "Enter title: ";
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;

  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";

  return 0;
}

The result is:
Enter title: Invasion of the body snatchers
Enter year: 1978

You have entered:
Invasion of the body snatchers (1978)

Nesting (annidate) Structures

...
struct movies_t {
  string title;
  int year;
};

struct friends_t {
  string name;
  string email;
  movies_t favorite_movie;
} charlie, maria;

friends_t * pfriends = &charlie;
...
// After that it would be valid:
charlie.name
maria.favorite_movie.title
charlie.favorite_movie.year
pfriends->favorite_movie.year
...

My website: http://www.lucedigitale.com

Reference: http://www.cplusplus.com/doc/tutorial/structures/

By |C++, Video Games Development|Commenti disabilitati su C++ Data Structures – Arrow Operator

C++ Pointers and Dynamic Memory

C++ Pointers and Dynamic Memory

With pointers all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

new – new[]

Dynamic memory is allocated using operator new.


// In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence
int * foo; 
foo = new int [5];

delete – delete pointer

In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory.


// clear the memory
delete pointer;
delete[] pointer;

nothrow

When a memory allocation fails, instead of throwing a ‘bad_alloc exception’ or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution normally.


// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  // no bad_alloc exception ##################
  p= new (nothrow) int[i];
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    // clear the momory #######################
    delete[] p;
  }
  return 0;
}

The result is:
How many numbers would you like to type? 3
Enter number : 12
Enter number : 23
Enter number : 34
You have entered: 12, 23, 34,

For italian people: come funziona?
1. p= new (nothrow) int[i]; -> evita che termini l’ersecuzione del software per un ‘bad_alloc exception’

2. alloca i valori di input utente cin <<... e li visualizza cout >>…

3. delete[] p; -> ripulisce la memoria

By |C++, Video Games Development|Commenti disabilitati su C++ Pointers and Dynamic Memory