Problems with functions

I'm trying to get the code below to call out what you say but its not any help for me? Sorry if I do any thing wrong I am new to this form
#include <iostream>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Calling the varibles
double favnum;
int hybridnum;
//the home made function
void myfun(int x)
{
    using namespace std;
    cout << "Whats your favorite number?"; 
    cin >> favnum;
    hybridnum = favnum;
    cout << "buckys favorite number is also "; cout << x;
}
//the main function
int main()
{
    myfun(hybridnum);
}
Last edited on
Use [ code][ /code] tags (without the spaces) to make your code easy on the eyes.

Anyway, you messed something up: you never assigned a value to 'x' before outputting it. You read in a variable to favnum and copy it to hybridnum, but 'x' never changes. Change hybridnum = favnum; to x = favnum;.

Another possible problem is your scope management: you're passing hybridnum to myfun(), but hybridnum is already known in myfun, because it is global. What happens is that 'x' in your function call becomes a copy of 'hybridnum' [which has no value at time of copying!], which means that myfun actually has two versions of 'hybridnum': hybridnum itself (globally) and x (temporary locally).

Also, something that might confuse you at first: if you pass a variable by value (like you did), a copy is used throughout the function call, but the argument variable itself is never changed. At the end of myfun(hybridnum), hybridnum still won't have a value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
//Calling the varibles
double favnum;
//the home made function
void myfun(int x)
{
    using namespace std;
    cout << "Whats your favorite number?"; 
    cin >> favnum;
    x = favnum;
    cout << "buckys favorite number is also "; cout << x;
}
//the main function
int main()
{
    return 0;
}

I did this but now it dosen't even say anything would this be the right way to fix it?
Last edited on
a) You're not calling your function. Of course nothing happens.
b) 'x' has no point outside myfun. Rather than making it a parameter, you should just declare it inside your function.
c) Why did you put using namespace std; inside your function?
I figured it out
Gaminic I used it because it calls errors if I don't I use mac so it might be diffrent
Topic archived. No new replies allowed.