Stuart B Stuart B - 10 months ago 103
C++ Question

C++ Boolean Function Operands

So I've started working with c++ for my university classes and it's been going really well so far. There's a dilemma I'm having with a current question and I've got the basic code structure all figured out, there's just one problem with my output.

What I'm looking for e.g;

if (bool variable = true){

output

else
alternate output


I'm aware that this isn't a free debugging service place, but it would really help me in future projects as well and there aren't any bugs, it executes just fine.

My code:

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

//function prototypes
bool calculateBox(double, double, double, double *, double *);

int main()
{
//defining variables
double length, width, height, volume, surfaceArea;

cout << "Hello and welcome to the program.\nPlease enter the dimensions for the box in [cm](l w h): ";
cin >> length >> width >> height;
calculateBox(length, width, height, &volume, &surfaceArea);

if (bool calculateBool = true) {
cout << "Volume: " << volume << "cm^3" << endl << "Surface Area: " << surfaceArea << "cm^2" << endl;
}
else
cout << "Error, value(s) must be greater than zero!" << endl;

system("pause");
return 0;
}

//functions
bool calculateBox(double length, double width, double height, double * volume, double * surfaceArea) {
if ((length > 0) && (width > 0) && (height > 0)) {
*surfaceArea = length * width * 6;
*volume = length * width * height;
return true;
}
else
return false;
}


*Key, if the values do not meet the requirements, the output displays not the error message, but a strange string for surfaceArea and volume. It appears to skip over the 'else' statement.

My question - does my error lie within the return statements in the function? Or is it a logic problem with my 'if' statement in the main method?

Answer Source

In the statement

if (bool calculateBool = true) 

the bool calculateBol part will cause a local variable named calculateBool be defined as a bool. The = true part means to assign what's on the left of =to the value true. The whole bool calculateBool = true will therefore be true so that that the else clause will never be executed.

Note that the the occurence of a single = in a condition should always ring the bell that bad signs could happen. Because comparing for equality is ==.

This being said, you could write:

 if (calculateBox(length, width, height, &volume, &surfaceArea)) {

or if you need the value later on:

bool calculateBool = calculateBox(length, width, height, &volume, &surfaceArea);
if (calculateBool) {  // or calculateBool==true if you prefer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download