Trying out functions for the first time, what am I doing wrong?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Trying out functions for the first time, what am I doing wrong?
I appreciate any help that I can get:
Write a program that takes as input an arithmetic expression and verifies if it is correct. The user will input the expression in the following format:
operator num1 num2 num3
The program should now check if:
num1 operator num2 = num3
If it is correct the program should print:
num1 operator num2 = num3
If it is not correct the program should print:
num1 operator num2 != num3
I did it without using functions but now I'm trying to test them out
What's wrong with the code?
Code:
#include <iostream>
using namespace std;
void user ()
int output()
int main ()
{
char op;
int x, y, z ;
user ()
output ()
return 0;
}
user ()
{
char op;
int x, y, z;
cout << "Enter an arithmetic Expression:" ;
cin >> op >> x >> y >> z ;
return;
}
output ()
{
char op;
int x, y, z ;
if (op = '+' &&
x + y == z)
cout << x << "+" << y << "==" << z <<endl;
else if ( op == '-' &&
x - y == z)
cout << x << "-" << y << "==" << z <<endl;
else if ( op == '*' &&
x * y == z)
cout << x << "*" << y << "==" << z << endl;
else if ( op == '/' &&
x / y == z)
cout << x << "/" << y <<"="<< z << endl;
else if ( op == '%' &&
x % y == z)
cout << x << "%" << y << "==" << z << endl;
else if ( op == '+' &&
x + y != z)
cout << x << "+" << y << "!=" << z << endl;
else if ( op = '-' &&
x - y != z)
cout << x << "-" << y << "!=" << z << endl;
else if ( op = '*' &&
x * y != z)
cout << x << "*" << y << "!=" << z << endl;
x / y != z
else if ( op = '/' &&
x / y != z)
cout << x << "/" << y << "!=" << z << endl;
else if ( op = '%' &&
x % y != z)
cout << x << "%" << y << "!=" << z << endl;
else
cout << "You are an idiot. This operator clearly does not exist. Try again, and do better" << endl;
return int ;
}
I did it without using functions but now I'm trying to test them out
What's wrong with the code?
Variables have scope.
Declaring the same variable name in two different scopes gives you two different variables with the same name.
Have you learned about structures yet? Have you learned about passing by reference yet?
I don't want to do your homework for you. But most methods I could suggest (rather than demonstrate) probably involve techniques you don't know yet.
The common way to do the operation you described is to define a structure type that contains all of the results of the user() function, which are also all of the inputs of the output function. Then declare one instance of that structure in the main function and pass it by reference to the other functions.
That is, of course, not the only possible way to do it.
The simple, working but bad way to do it is to declare the individual variables once outside of all the functions, so they are global and accessible by all functions. That pretty much defeats the point of splitting the work into functions. But it does split the work into functions and it does work. In a sufficiently beginner assignment in a poorly taught programming class, that might be the expected answer.
I don't want to do your homework for you. But most methods I could suggest (rather than demonstrate) probably involve techniques you don't know yet.
I was still editing my post when you asked ...
Quote:
Originally Posted by carlosk711
So how should it look?
Sorry. That is not the way we are supposed to provide homework help. We are supposed to provide explanations of why what you tried didn't work. Sometimes suggestions are also appropriate. But doing the assignment for you is not appropriate.
variables are only accessible within the same context from which they were declared.
so if i have two functions, both these variables actually access a different piece of memory:
Code:
int main()
{
int x = 3;
}
void add5tox()
{
int x;
x+=5;
}
so basically if i were to set x in one function, the x variable in the other function would not change.
In order to have a variable accessible in two functions i would need to declare it in a context that is accessible from both functions, like the following:
Code:
int x;
int main()
{
x = 3;
}
void add5tox()
{
x+=5;
}
if i declare the x variable OUTSIDE the two functions, at the same level that the functions themselves are defined, then i am able to use it from both, so that if i change it with one function, that value is available to the other function.
This method, however, is not generally a good practice, as it does not create modular code (i.e. code that can easily be re-used in different situations, like with different values). For example, does not allow you to easily use your function with different inputs, because it always acts on the x variable.
You want your code to be modular, think of a game cartridge being plugged into a game system. To do something like this, you'd pass the variables by reference as arguments to the function. Although it may be a little confusing at first, requiring an understand of pointers (which can be rather tricky at first) it actually makes a lot more sense than doing it like above, and allows you to use your functions with any input you wish to pass to it:
Code:
int main()
{
int x = 3,
y = 1;
add5(&x);
add5(&y);
}
void add5(int *n)
{
*n += 5;
}
You'll notice this is much cleaner and easier to read and understand than if you tried to do it using the method above, and allows me to write a single function to act on both variables:
Code:
int main()
{
int x = 3,
y = 1;
add5tox();
add5toy();
}
void add5tox()
{
x+=5;
}
void add5toy()
{
y+=5;
}
Now imagine how unpractical this would be if you were to have an array of 100 values and you wanted to add 5 to each... you'd need 100 functions, each acting on a different position in the array. Definitely not a good idea:
Also, instead of using a giant if block, i would use a simple switch-case statement instead:
Code:
char c;
switch
{
case 'a':
// do something when c=='a'
break;
case 'b':
// do something when c=='b'
break;
default:
// do something when nothing matches
break;
}
To do something like this, you'd pass the variables by reference
...
Code:
...
add5(&x);
...
void add5(int *n)
The original question was about C++, not C.
Whether "pass by reference" is an appropriate name in C for the technique you showed could be argued either way. But it is certainly not an appropriate name for that technique in C++.
C++ has pass by reference as a language feature. So the technique one should call "pass by reference" in C++ is actual pass by reference, not passing the address to a pointer.
Location: North of Boston, Mass (North Shore/Cape Ann)
Distribution: CentOS 7.0 (and kvm/qemu)
Posts: 91
Rep:
Emotional Response
Hi.
Now that your problem is resolved, in oh so many ways, at oh so many levels, will you permit an emotional response ?
Why do programmer have to pound everything with the hammer of arrogance? It seems, by your post and example, that you've got a complete naivete about this programming language (and forums), yet it seems the purpose of your function is to get to this cout:
Quote:
cout << "You are an idiot. This operator clearly does not exist. Try again, and do better" << endl;
Having dealt with programmers, old and new, for decades, dealt with customers and partners for decades, this chip-on-the-shoulder and "I'm the smartest person in the room" non-sense just makes it harder to get things done -- especially when the attitude generally is so unmerited; and those that merit rarely exhibit the attitude.
Like I said, this is just a emotional response to your query especially contrasted with the gentleness and quality of the help and advice you received.
Best to you continuing to sharpen programming skills.
@LQParsons: when you consider that a program like this will generally only be run by its programmer, it could be an example of humility rather than arrogance.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.