Structuring C++
Go to solution
Solved by Ciccioo,
the idea is that you should have your declarations in a header file (.h), and the implementations of the declared things in an implementation file (.cpp)
i'll slightly modify your code to make it more how it's supposed to be, so let's start from this code:
#include <iostream>using namespace std;int calculation (int x, int y, char operation){ int c; switch (operation) { case '+': c = x + y; break; case '-': c = x - y; break; case '*': c = x * y; break; case '/': c = x / y; break; } return c;}int main(){ int a, b, c; char operation; cout << "Enter Calculation: "; cin >> a >> operation >> b; c = calculation(a,b,operation); cout << c; return 0;}
now you can split into
int calculation(int x, int y, char operation);
#include "calculations.h" // i need the declaration of what i'm about to implementint calculation (int x, int y, char operation){ int c; switch (operation) { case '+': c = x + y; break; case '-': c = x - y; break; case '*': c = x * y; break; case '/': c = x / y; break; } return c;}
finally, the file that uses the function, main.cpp
#include <iostream>#include "calculations.h" // with this, i bring into this file all the functionalities that are declared into calculations.h, without needing to know their implementationsusing namespace std;int main(){ int a, b, c; char operation; cout << "Enter Calculation: "; cin >> a >> operation >> b; c = calculation(a,b,operation); cout << c; return 0;}
you pretty much want to keep definitions seperate from implementations
your code didn't compile because the variable a, b, c, and operation don't exist in the other files. there are ways to make variables visible across files, but in this case (and very very very often) it's a better idea to stay away from global variables and keep them local to the function, using parameters to reach data from around the program

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now