C++ function

Questions about programming languages and debugging
Post Reply
User avatar
hpprinter100
Fame ! Where are the chicks?!
Fame ! Where are the chicks?!
Posts: 214
Joined: 19 Oct 2007, 16:00
16
Contact:

C++ function

Post by hpprinter100 »

Code i am writing is a program that the user puts in a pair of cities and then outputs the distance between them. I have stored the miles in a 2-d array. It works with 2 sets of if statements but i know a function would be better.

I commented the code to describe the problem

" onclick="window.open(this.href);return false;" onclick="window.open(this.href);return false;

User avatar
Gogeta70
^_^
^_^
Posts: 3275
Joined: 25 Jun 2005, 16:00
18

Re: C++ function

Post by Gogeta70 »

You're passing the variable "i" as a parameter to your function and then returning that parameter. Generally, you want to avoid this kind of thing. Instead, try this:

Code: Select all

void CitySelect(string City)
{
int i = 0;

if(City == "Coventry"){
        i = 0;
}
else if(City == "London"){
        i = 1;
}
else if(City == "Peterborough"){
        i = 2;
}
else if(City == "Birmingham"){
        i = 3;
}
else if(City == "Manchester"){
        i = 4;
}
 
return i;
 
}
Edit: Ah, i just noticed what you're trying to do. If you want to pass a variable to your function and have your function modify that variable, you'll either have to pass it by reference or pass a pointer to the function.

As the function is now (what i put above), you'll have to do this:

Code: Select all

y = CitySelect(City1);
Hope this helps.
¯\_(ツ)_/¯ It works on my machine...

User avatar
hpprinter100
Fame ! Where are the chicks?!
Fame ! Where are the chicks?!
Posts: 214
Joined: 19 Oct 2007, 16:00
16
Contact:

Re: C++ function

Post by hpprinter100 »

Thank you, working now :) :D

User avatar
Gogeta70
^_^
^_^
Posts: 3275
Joined: 25 Jun 2005, 16:00
18

Re: C++ function

Post by Gogeta70 »

No problem. ^_^
¯\_(ツ)_/¯ It works on my machine...

Post Reply