Warning: Function will always return True [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have an isPrime function that is always returning true, regardless of the inputted number. This is the same for a couple other bool functions in my program.
My simple isPrime function:
bool isPrime(mpz_class num)
{
bool prime = true;
for (int i=2; i<num; i++)
if (num % i == 0)
prime = false;
return prime ;
}
Calling it (I suspect this is where the problem is but I don't know what the problem is):
do
{
do
{
cout << "Enter Prime 1: ";
getline(cin, sa);
isNum(sa);
firstPrime = sa;
}
while(!isNum);
isPrime(firstPrime);
}
while(!isPrime);
The isNum function is also returning "true" every time.
Runtime error:
warning: the address of 'void isNum(std::string)' will always evaluate as 'true' [-Waddress]|
Does anyone see the problem?

You need to store the return value from the call to isNum() before you can check it in the while look. What you're doing now with
while(!isNum)
is that you're checking the address of the function and not it's return type. What you probably mean to do is something like this:
bool isPrimeRetVal;
do
{
bool isNumRetVal;
do
{
cout << "Enter Prime 1: ";
getline(cin, sa);
isNumRetVal = isNum(sa);
firstPrime = sa;
}
while(!isNumRetVal);
isPrimeRetVal = isPrime(firstPrime);
}
while(!isPrimeRetVal);
Note the same issue with while(!isPrime).

You ignore the return value of isPrime and instead check the value of isPrime (which doesn't change, it's always a valid function).

You are not calling the function by merely mentioning its name, e.g. with while (!isNum).
The function name in that context evaluates to a pointer to that function. Since all non-null pointers evaluate to boolean true and a pointer to any function cannot be equal to the null pointer, isNum always evaluates to true and !isNum is always false.
Instead of this:
do { ... isPrime(x); } while (!isPrime);
you need to write something more like this:
do { ... } while (!isPrime(x));

These two lines:
isPrime(firstPrime);
while(!isPrime);
combine to suggest you're not clear on how functions are called in C++. The first line calls the function and then throws the result away. The second line doesn't even call the function, it just looks at its address (which will never be zero).
You probably want:
while(!isPrime(firstPrime));
This passes firstPrime to the function, and then looks at the return value of the function.

You are not using return value of isPrime function. IsPrime is a function and you should store its value in some variable and use that variable in while loop.
The same goes with the isNum variable.

Related

C++ beginner got 42 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Getting Douglas Adams vibes here...
I just started out with c++ and doing some code challenges right now.
The current challenge is to create a function that takes a number as its only argument and returns true if it's less than or equal to zero, otherwise return false.
However, when I run the program I get the number 42??
I actually don't need help for the challenge itself, I just wonder if someone could explain why I get this result :)
#include <iostream>
#include <string>
using namespace std;
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
}
int main()
{
cout << lessThanOrEqualToZero(5);
}
The function bool lessThanOrEqualToZero(int);, as defined, makes your program have undefined behavior since not all paths in the function leads to the function returning a bool that you declared that it should return. Specifically: If num > 0 is true the function doesn't return a value.
When a program has undefined behavior, you can't trust anything it does. Your program could therefore print just about anything or nothing, crash or do something completely wild.
In some compilator implementations, a value could be picked from the stack where it expects to find the promised bool and then print whatever that value was (42 in your case). The stack will then be corrupt. Other implementations may compile it into a program that does something completely different. You'll never know.
The solution is to make sure that all paths leads to a return:
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
return false;
}
This however better written as:
bool lessThanOrEqualToZero(int num)
{
return num <= 0;
}
otherwise return false
Well then you do need to return false otherwise.

Why this recursive function only work when used ELSE [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I made this function that returns the number of digits in an integer:
it works fine when I used ELSE to return the count
int getIndex(int number, int count) { // at first call count is 0
number /= 10;
if (number > 0){
getIndex(number,++count);
}
else{
return ++count;
}
}
but when I first tried to execute without ELSE statement I thought function will be called recursively till IF condition is not met and then only it will encounter the return statement
And function will exit there as integer is returned, but
actually
if the number contains more than one digit, doesn't matter how many time it increase with recursive call it outputs 2
Just curious where as to why I am getting my concept wrong
it works fine when I used ELSE
Actually, the behaviour of the shown program is undefined. If the if branch is entered, then no return statement will be reached, and the behaviour of the program will be undefined.
When you remove the else statement and instead return unconditionally, the behaviour is well defined: The function will always return count + 1 or count + 2 depending on the value of number (which isn't correct).
Consider this, where do you use the value of the recursive function call? Nowhere; you simply discard the value. Would it make sense to return that value to the caller? Yes, it would. If only you returned within the if branch, the behaviour would be correct.
return getIndex(number,++count);
Then it won't matter whether the recursion-terminating branch is within else or not, it will only be executed if the if branch is not executed:
You are missing a return before the recursive call.
By default, it returns 0 (for some compilers).
Edit:
But actually the code should have looked like this:
int getIndex(int number) {
if (number > 0) {
return getIndex(number/10) + 1;
} else {
return 0;
}
}

How to write an if-else statement in C++? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!

Calling bool function inside if parameters [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
so I have a C++ bool function that I've written that looks like this:
bool EligibileForDiscount(const char CompanyUsed, const char CompanySubscribed)
{
bool eligible = false;
if (CompanyUsed==CompanySubscribed)
eligible = true;
return (eligible);
}
Now in my main() this function is called as the only parameter for an if statement:
if (EligibleForDiscount(CompanyUsed, CompanySubscribed))
{
ApplyDiscount(Cost, CompanySubscribed);
cout << "\nAfter your discount, your rental is: $"
<< fixed << showpoint << setprecision(2) << Cost << ".\n";
}
The main function was written by my teacher and we wrote the other functions, so this if statement isn't supposed to be changed.
So I understand what the if statement is trying to accomplish, by basically saying "if (true) do this..." since the EligibleForDiscount will return a boolean value.
However, g++ is giving me an error with the if statement, telling me that EligibleForDiscount is not declared in this scope.
But I'm not trying to use it as a value but as a call to a function.
It may be because of two reasons:
You misspelled the function name when called : if (EligibleForDiscount(CompanyUsed, CompanySubscribed)) should be written like your implementation of the function, which is EligibileForDiscount.
This can happen if you forgot to declare the prototype of the function, which is an indicator to the program that you're going to use that function. You simply need to write somewhere before you use the function bool EligibileForDiscount(const char , const char)
One of these should work!
Because : EligibileForDiscount != EligibleForDiscount with an additional "i", just a typo.
p.s. you can write EligibleForDiscount like this:
bool EligibleForDiscount(const char CompanyUsed, const char CompanySubscribed)
{
return CompanyUsed==CompanySubscribed;
}

Passing a LPDWORD as out parameter [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am new to C++ and I need to create a function with this structure:
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
DWORD myDword = 1;
myLpdword = &myDword;
return true;
}
int main(){
DWORD outDword = 20;
myfunc(&outDword);
cout << outDword << end1;
return 0;
}
I expected that the value of outDword would be 1 (changed by myfunc), but the value is not changed by myfunc.
Please, can you give me a hint to solve this problem?
Like this
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
*myLpdword = 1;
return true;
}
Out parameter is not something that means anything in C++. MS use it but only because they are using a consistent terminology across different languages.
In C++ terms what you did is pass a pointer to the variable you want to modify to myfunc. What the above code does is take that pointer and dereference with the * operator it to modify the variable you wanted modified.
I like that you're writing small test programs to check your understanding of C++. But as others said there's no real substitute for a decent book. Any C++ book is going to cover this.
You passed in a pointer to outDword.
myLpdword is now a pointer to outDword.
You then changed myLpdword to be a pointer to myDword.
You never did anything with the VALUE of outDword.
You assigned the pointer of a variable that will not exist after exiting the function body (read on scopes in C/C++.
To solve your problem, assign the value of the variable to the dereferenced pointer, like so: *myLpdword = myDword;. It would also be wise to check that the value of the pointer is not null before dereferencing it like this: if (myLpdword == 0) { return; } . This check doesn't guarantee that the pointer is safe to assign to, but Atleast guards you against null pointer access.
In C++ this is called pass-by-reference. You denote it with an ampersand in the function signature:
bool myfunc(DWORD &myDword) {…
The ampersands you are using now are actually getting the address of the variables, so you should remove those.