Arkarin Arkarin - 3 months ago 8
C++ Question

C++ if command reading true despite false

I've been trying to write a program that factors number for me but my if statement keeps running despite the condition being false. In function factor, I use modf to separate the decimal from the integer and store it as

c
. The if statement checks if
c = 0
which means the number divided evenly.

Below is my source code with results below it.

#include <iostream>
#include <math.h>
using namespace std;

int factor(double b);
int i = 1;
int factors[] = {1};

int main()
{
int a;
double b;
cout << "Please enter a integer to Factor: ";
cin >> a;
b = a;
factor(b);
return 0;
}

int factor(double b)
{
double c;
double d;

for ( ; c != 0 ; i++)
{
cout << "for loop executed" << endl;
c = modf (b/3, &d);
cout << c << endl;
if (c = 0.00);
{
cout << 3 << endl;
factors[i] = 3;
continue;
}
c = modf (b/5, &d);
if (c = 0);
{
cout << 5 << endl;
factors[i] = 5;
continue;
}
c = modf (b/7, &d);
if (c = 0);
{
cout << 7 << endl;
factors[i] = 7;
continue;
}
c = modf (b/11, &d);
if (c = 0);
{
cout << 11 << endl;
factors[i] = 11;
continue;
}
c = modf (b/13, &d);
if (c = 0);
{
cout << 13 << endl;
factors[i] = 13;
continue;
}
c = modf (b/17, &d);
if (c = 0);
{
cout << 17 << endl;
factors[i] = 17;
continue;
}
}
return c;
}


In cmd it prints

Please enter a integer to Factor: 50
for loop executed
0.666667
3


50/3=16.6 repeating

modf of 16.6666666 outputs 16 and 0.666667

0.666667 does not equal 0 so I'm confused.

Answer

There are multiple bugs in the shown code.

double c;

for ( ; c != 0 ; i++)

The c variable is not initialized, then its value gets compared to 0. This is undefined behavior.

    if (c = 0.00);

There are two bugs on one line, here.

= is the assignment operator, not a comparison operator. The if expression will always evaluate to false, here.

Then, the extra semicolon that follows the closing parenthesis terminates the if statement. Immediately afterwards:

    {
        cout << 3 << endl;
        factors[i] = 3;
        continue;
    }

This will always get executed, since it is not really a part of the preceding if statement.

== is the comparison operator.

= is the assignment operator.

A semicolon does not follow the if() expression. If it does, it gets interpreted as an empty statement.

But, the problems are not finished yet:

int i = 1;
int factors[] = {1};

This declares the array factors, containing one value. The size of the array is 1 element.

for ( ; c != 0 ; i++)

   // ...

        factors[i] = 3;

This will attempt to assign elements of the array that do not exist, running off past the end of the array and corrupting memory.

I'm surprised that all of this manages to run at all, for a significant number of iterations, but, well, that's what "undefined behavior" means.