Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment a referenced variable by 1

Tags:

c++

loops

I am new to c++ and I am trying to increase cars starting with value 50, but only increase by one if the youdamage is greaters than cardamage. I want cars to hold its value for the next time it does through the loop. I hope this makes sense.

int Power (int &car);

int main(){
    int car = 50;
    // ...
    // ...
    // ...

    int carDamage = 0;
    int yourDamage = 0;
    // pick a random number between 1 to 50
    yourDamage = 0 + rand() % (50 - 0 + 1);
    carDamage = 0 + rand() % (50 - 0 + 1);
    cout << "You hit the car and cause damage of: " << carDamage << endl;
    cout << "The car hits you and causes damage of: " << yourDamage << endl;
    cout << endl;

    if(carDamage < yourDamage)
    {
        cout << "You win" << endl;
        cout << "You gain strength." << endl;
        cout << endl;
        int car = car + 1;
    }
    else
    {
like image 748
SilverNightaFall Avatar asked Oct 31 '11 21:10

SilverNightaFall


3 Answers

You're declaring a new variable shadowing the original one.

change

int car = car + 1;

to

car = car + 1;
like image 58
littleadv Avatar answered Oct 14 '22 08:10

littleadv


You need to reassign to the same variable. You are declaring a new variable.

Change this:

int car = car + 1;

To this:

++car;
like image 9
Mark Byers Avatar answered Oct 14 '22 07:10

Mark Byers


By doing this:

int car = car + 1;

You are re-defining car as an integer.

see:

#include <stdio.h>
int car;
int main() {
    car = 0;
    for (int i = 0; i < 10; i++) {
        int car = 0;
        car++;
    }
    printf("%3d", car);
}

vs

#include <stdio.h>
int car;
int main() {
    car = 0;
    for (int i = 0; i < 10; i++) {
        car++;
    }
    printf("%3d", car);
}
like image 1
Martin Samson Avatar answered Oct 14 '22 09:10

Martin Samson