Passing structures to a function?
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Spaceship;
Spaceship move_ship(Spaceship ship);
void update_location(Spaceship ship, int &count);
Spaceship get_new_ship(Spaceship ship);
struct Spaceship
{
int x_coordinate;
int y_coordinate;
};
Spaceship get_new_ship()
{
Spaceship ship;
ship.x_coordinate = 0;
ship.y_coordinate = 0;
return ship;
}
void update_location(Spaceship ship,int &count)
{
std::cout << "Ship is now located at (" << ship.x_coordinate << "," << ship.y_coordinate << ")." << endl;
if (ship.x_coordinate > 1024 || ship.y_coordinate > 768)
{
std::cout << "Ship has left the screen. \n";
count = 0;
}
}
int main()
{
int count = 1;
Spaceship ship = get_new_ship();
do{
ship.x_coordinate = ship.x_coordinate + 10;
ship.y_coordinate = ship.y_coordinate + 10;
update_location(ship,count);
}
while(count != 0);
}
I've managed to output all the ship's location after it make each 10 units movement towards north east using the code above, without putting the 'add 10 coordinates' in a function.
However if I put it this way (put it in the function Spaceship move_ship(), coordinate x and y remains zero. What is wrong with my function? ):
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Spaceship;
Spaceship move_ship(Spaceship ship);
void update_location(Spaceship ship, int &count);
Spaceship get_new_ship(Spaceship ship);
struct Spaceship
{
int x_coordinate;
int y_coordinate;
};
Spaceship get_new_ship()
{
Spaceship ship;
ship.x_coordinate = 0;
ship.y_coordinate = 0;
return ship;
}
Spaceship move_ship(Spaceship ship)
{
ship.x_coordinate = ship.x_coordinate + 10;
ship.y_coordinate = ship.y_coordinate + 10;
return ship;
}
void update_location(Spaceship ship,int &count)
{
std::cout << "Ship is now located at (" << ship.x_coordinate << "," << ship.y_coordinate << ")." << endl;
if (ship.x_coordinate > 1024 || ship.y_coordinate > 768)
{
std::cout << "Ship has left the screen. \n";
count = 0;
}
}
int main()
{
int count = 1;
Spaceship ship = get_new_ship();
do{
move_ship(ship);
update_location(ship,count);
}
while(count != 0);
}