I am supposed to write a program that should read from input numbers in the main() part, and then make some calculations in other bool functions. I don’t want to insert the whole arrays of the numbers and all the other parameters in the functions everytime i call them.
My question is this: Can i make somehow in c++ to read input in some variables, but in a way that other functions outside of main() will also “know” this variables and what’s inside them so i don’t have to put a lot of arguments when i call the functions ?
This is the code:
#include <iostream>
using namespace std;
inline bool del(int n)
{
int i;
for(i=0;i<s1;i++)
{
if((n % a[i]) == 0) return true;
}
return false;
}
inline bool ned(int n)
{
int i;
for(i=0;i<s2;i++)
{
if((n % b[i]) != 0) return true;
}
return false;
}
int main(void)
{
int s1, s2, a[25], b[25];
int m, n, i, k=0;
bool d, nd;
cin >> s1 >> s2 >> m >> n;
for(i=0;i<s1;i++)
cin >> a[i];
for(i=0;i<s2;i++)
cin >> b[i];
for(i=m;i<=n;i++)
{
d = del(i);
nd = ned(i);
if(d == true && nd == true) ++k;
}
cout << k << endl;
return 0;
}
int s1, s2, a[25], b[25] <- These are the vars i need to be seen by the other functions (because i use them as you can see).
I tried declaring them like global, but that didn’t work, i got errors like “was not declared in this scope” .
Thank you for the help.
Making variables global for this reason is bad habit. Either just pass the arrays to the functions, or make the whole thing into an object and make the arrays and functions members of the class. This is what OOP is about.