one static variable to multiple copies - c++

Is there a way to have a static variable have multiple copies in C/C++?
The following code have a static variable - miles. How to achieve that runner1() and runner2() have its own miles copy but keep miles as static?
test.h
static int miles;
extern int get_miles();
test.c
#include "test.h"
int get_miles() {
miles = miles + 1;
return miles;
}
user.c
#include <stdio.h>
#include "test.h"
extern void runner1();
extern void runner2();
void runner1() {
int i;
for(i=0;i<5;i++) {
printf("runner1 runs %0d miles\n", get_miles());
}
}
void runner2() {
int j;
for(j=0;j<5;j++) {
printf("runner2 runs %0d miles\n", get_miles());
}
}
int main() {
runner1();
runner2();
}
https://www.edaplayground.com/x/3G7h

This is contradictory: You want two things that are different and equal at the same time.

Related

Undefined Reference Error/ Dynamically Calling Functions

Hi I am working on a program that involves a Main.cpp, Connect4.cpp, and Connect4.h file. When I compile my program I am getting an error in the Main file saying that my playGame function is an undefined reference. I am compiling both files together(main first) I believe something is wrong in the way I am trying to dynamically call the function playGame. Any input would be much appreciated!
Main.cpp
#include <iostream>
#include <array>
#include "Connect4.h"
void playGame();
using namespace std;
int main()
{
Connect4 *ptr;
ptr=new Connect4;
ptr-> playGame();
delete ptr;
}
Connect4.cpp
#include <iostream>
#include <array>
#include "Connect4.h"
char gameBoard[9][7];
int rows;
int columns;
using namespace std;
void playGame()
{
void display();
int selectColumn(bool);
int tokenPlacement(char token, int columns);
bool winOrLose();
cout<<"Welcome to Connect Four.";
for(int i=0; i<rows;++i)
{
for(int j=0; j<columns; ++j)
{
gameBoard[i][j]=' ';
}
}
bool player1Turn=true;
char winner='n';
int column =0;
while(true){
display();
column=selectColumn(player1Turn);
if(player1Turn==true)
{
tokenPlacement('x',column);
player1Turn=false;
}
else
{
tokenPlacement('o', column);
player1Turn=true;
winner= winOrLose();
if(winner!='n')
{
break;
}
}
cout<<"Winner is:"<<winner;
}
Connect4.h
#ifndef CONNECT4_H_
#define CONNECT4_H_
#include
using namespace std;
class Connect4 {
public:
static void playGame();
private:
void display();
int selectColumn(bool);
int tokenPlacement(char, int);
bool winOrLose();
char gameBoard[9][7];
};
#endif /* CONNECT4_H_ */

C++ ADT proper header files?

I am making my own ADT, the issue I am having is the program won't compile as it crashes with an error C:\Dev-Cpp\Makefile.win [Build Error] [mainpoly.o] Error -1073741819.
I am not sure what that means, but i think it has to do with how i am naming my files (.h,.cpp). Right now I want to get my program to compile so I can test out the bugs in my ADT, i just need help in getting the program to compile at this point, not the errors in the program itself, thank you. I dont know what extension to give to what file (if thats even the core issue) Also, not sure hot to separate the three programs here on the forums, sorry.
Here are the three files
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <string>
#include <vector>
struct v{
int coe;
int deg;
};
class polynomial{
private:
vector<v> poly;
public:
~polynomial();
polynomial(int, int);
int degree();
int coeffecient(int);
void changeCoeffcient(int, int);
void mulpoly(int, int);
int addpoly(int, int);
int getpoly();
};
#endif
#include "polynomial.h"
#include <vector>
polynomial::polynomial(int coeffecient, int degree){
coe=coeffecient;
deg=degree;
v t;
t.co=coe;
t.de=deg;
poly.push_back(t);
}
polynomial::~polynomial(){
delete[];
}
int polynomial::degree(){
return poly;
}
int polynomial::coeffecient(power){
int i=power;
int val;
for(int z=0;z<t.size;z++){
if(i=t.de[z]){
val=t.co[z];
break;
}
else{
return 0;
}
}
return val;
}
void polynomial::changeCoeffcient(int newCoeffcient, int power){
int i=power;
for(int z=0;z<t.size;z++){
if(i=t.de[z]){
t.co[z]=newCoeffcient;
break;
}
else{
return 0;
}
}
}
void polynomial::mulpoly(int coeffecient, int mul){
int i=coeffecient;
for(int z=0;z<t.size;z++){
if(i=t.co[z]){
t.co[z]*=mul;
break;
}
else{
return 0;
}
}
}
#include <stdlib.h>
#include <iostream>
#include <polynomial.h>
using namespace std;
int main(){
int i;
polynomial poly(3,5);
i=poly.degree();
cout<<"The value is: "<<i;
system("PAUSE");
return 0;
}

Passing Pointers to Classes in C++

I am trying to pass a pointer into my classes function, have it incremented, and have the variable retain it's value using pointers. Heres my code, it doesnt increment.
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int y;
};
test::test(int * currentY):
y(*currentY)
{
}
int test::addTo()
{
y++;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
int * number = &pointedAt;
test t(number);
t.addTo();
cout <<*number;
char f;
cin >>f;
}
}
This should do it:
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int *y;
};
test::test(int *currentY):
y(currentY)
{}
int test::addTo()
{
++*y;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
test t(&pointedAt);
t.addTo();
cout << pointedAt;
}
}
You have to store a pointer to the integer, so it refers to the same address as the original variable.

Classes in C++: Declaring an Instance

I have consulted many websites but have not successfully completed my code.
I am trying to write some code that spits out information about a car, once the user provides information. After compiling, the compiler says that "declaration does not declare anything." Here's the code:
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car()
{
}
void Car::accel()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
void Car::setSpeed(int newSpeed)
{
speed = newSpeed;
}
int Car::getSpeed()
{
return speed;
}
void Car::setMake(string newMake)
{
make = newMake;
}
string Car::getMake()
{
return make;
}
void Car::setYearModel(int newYearModel)
{
yearModel = newYearModel;
}
int Car::getYearModel()
{
return yearModel;
}
int main()
{
Car auto; //instance of class Car
int autoYear; //year of auto
string autoMake; //make of auto
int autoSpeed; //speed of auto
cout << "Enter the year model of your car. ";
cin >> autoYear;
cout << "Enter the make of your car. ";
cin >> autoMake;
auto.setYear(autoYear); //stores input year
auto.setMake(autoMake); //stores input make
}
And the header, Car.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car();
void accel();
void brake();
void setSpeed(int newSpeed);
int getSpeed();
void setMake(string newMake);
string getMake();
void setYearModel(int newYearModel);
int getYearModel();
};
#endif
I also have errors for missing semicolons every time my object auto appears ("expected ; before auto" and "expected primary-expression before auto"). What could be the problem?
auto is a keyword. You'll need to pick a different name.

How to use variables and functions declared in a header in C++

First of all this might be messy, because I'm pretty new to programming in general.
Well I'm making a rpg game and I want all my weapons to be in a file called Weapons.cpp.
I made it so that I got all of my global variables such as "weaponDamage" and "weaponName" in a header file called common.h so that I can access and manipulate those variables from both my main and my .cpp file. But the problem is that it can't seem to find those variables and functions in my header.
Here's some code:
common.h:
#include <string>
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED
//global variables
extern int pureDamage = 0;
extern int pureHealth = 0;
extern int weaponDamage;
extern int armorDefense;
extern int totalDamage = pureDamage + weaponDamage;
extern int totalHealth = pureHealth + armorDefense;
extern int totalLuck;
extern string starsign;
extern string weaponName;
//all weapons
void weaponSwordIron();
void weaponSwordGold();
void weaponSwordSwordOfTheHeavens();
void weaponBowSimple();
void weaponBowLongBow();
void weaponBowThunder();
void weaponStaffStaffOfFlames();
void weaponStaffStaffOfLightning();
void weaponStaffStaffOfAssKicking();
#endif // COMMON_H_INCLUDED
Weapons.cpp:
#include <iostream>
#include <string>
#include <common.h>
using namespace std;
void weaponSwordIron()
{
int weaponDamage = 5;
string weaponName = "Iron Sword";
}
void weaponSwordGold()
{
int weaponDamage = 8;
string weaponName = "Gold Sword";
}
void weaponSwordSwordOfTheHeavens()
{
int weaponDamage = 15;
string weaponName = "Sword Of The Heavens";
}
void weaponBowSimple()
{
int weaponDamage = 5;
string weaponName = "Simple Bow";
}
void weaponBowLongBow()
{
int weaponDamage = 8;
string weaponName = "Long Bow";
}
void weaponBowThunder()
{
int weaponDamage = 15;
string weaponName = "Thunder Bow";
}
void weaponStaffStaffOfFlames()
{
int weaponDamage = 5;
string weaponName = "Staff Of Flames";
}
void weaponStaffStaffOfLightning()
{
int weaponDamage = 8;
string weaponName = "Staff Of Lightning";
}
void weaponStaffStaffOfAssKicking()
{
int weaponDamage = 15;
string weaponName = "Staff Of Ass Kicking";
}
and a little piece of my main, the function called GiveWeapon():
void GiveWeapon()
{
system("cls");
if (starsign == "mage")
{
weaponSwordIron();
cout << weaponDamage;
cout << weaponName;
}
else if (starsign == "warrior")
{
weaponBowSimple();
}
else if (starsign == "archer")
{
weaponStaffStaffOfFlames();
}
else
{
ChooseStarsign();
}
AssignAttributes();
}
And yes I did remember to include common.h
Now the error my IDE Code::Blocks comes up with is : error: common.h: no such file or directory
I don't know why it comes up with that so please help.
Sorry for the long post and thanks in advance.
Use "common.h" instead of <common.h>.
The angled ones are for library files.
You should use "common.h" not < common.h>
weopens.cpp is mostly non-sense.
i tried compiling the following:
void a() {
int b = 5; }
int main()
{
a();
return 0;
}
and g++ didn't like the idea.
Where is your "common.h" placed? You must specify relative path to them from folder with the "Weapons.cpp".
At second, you define local variables in your functions. Your Weapons.cpp file must look like:
#include <iostream>
#include <string>
#include "relative/path/to/common.h"
//global variables
int pureDamage = 0;
int pureHealth = 0;
int weaponDamage;
int armorDefense;
int totalDamage = pureDamage + weaponDamage;
int totalHealth = pureHealth + armorDefense;
int totalLuck;
string starsign;
string weaponName;
using namespace std;
void weaponSwordIron()
{
weaponDamage = 5;
weaponName = "Iron Sword";
}
void weaponSwordGold()
{
weaponDamage = 8;
weaponName = "Gold Sword";
}
...
In addition to the header location issues and local variable shadowing that others have mentioned, I think you're also going to run into problems with multiple definition errors:
extern int pureDamage = 0;
The initializer on this declaration overrides the extern, so this variable will be not only declared but also defined in any compilation unit that includes this header. Your linker will complain.
When you really want to use globals across multiple files you'll need to define and initialize the variable once in a source file and declare it extern (with no initializer) in the header file. const variables are an exception to this, however.