Hello, I am new to this forum and C++. I am testing a function that will do something if another function is called or not.
Here is what I have but it is giving me an error message: Address of function will always return true
#include <iostream>
usingnamespace std;
staticint c{0};
bool calfunction(int);
void displayFunc(){
if(calfunction){
cout << "The function was called" << endl;
}else{
cout << "The function was not called" << endl;
}
}
int main(){
calfunction(2);
calfunction(4);
calfunction(6);
displayFunc();
cout << "calfunction was called " << c << " times" << endl;
return 0;
}
bool calfunction(int num){
int a {num * 2};
//cout << "a is: " << a << endl;
int b{num * 3};
//cout << "b is: " << b << endl;
c++;
returntrue;
}
void displayFunc(){
if(calfunction){
cout << "The function was called" << endl;
imagine that you are the computer and you read those instructions, ¿how do you interpret them?
¿do you really understand it as «check if somewhere, maybe long time ago, that function was called at least once»?
ask your classmates if they think the same.
¿do you expect to have stored a table of all the functions that were called, along with their parameters and return value? ¿what for?
I want displayFunc() to tell me rather calfunction() function was called or not and how many time. I got the "How many times part" but I don't get why the function will always return true and how to fix it.
I am looking for something similar to
while(true){} which I have tried but I get the same result: the function will always return true.
Yes but if the function is "not" called then the else part needs to print but if calfunction is always activated to true then the else part never happens which is my problem.
my program should be:
If calfunction is called
print it was called
else
print it was not called
But the error message says that calfunction will always be true. How do I make it false if it is not called?
#include <iostream>
size_t c {};
bool calfunction(int);
void displayFunc() {
if (c)
std::cout << "The function was called " << c << " times\n";
else
std::cout << "The function was not called\n";
}
int main() {
calfunction(2);
calfunction(4);
calfunction(6);
displayFunc();
}
bool calfunction(int num) {
int a {num * 2};
int b {num * 3};
++c;
returntrue;
}
But note it's not good practice to use global variables.