ripeisripe
ripeisripe

Reputation: 69

About arguments by default in C++

I am asking help to understand: - In this program:

#include <iostream>

int main() 
{
    int j = 0;
    int k = 1;
    int m = -1;
    int n = 1;

    int p = ((j * 300) - (4 * n) - (7 * m)); 

    if (int l = ((j * 300) - (4 * n) - (7 * m)) > 0) {
        std::cout << "l is egual: " << l - 1 << std::endl;
    }   
    else {
        std::cout << "l is negative: " << l << std::endl;
    }

    if (p > 0) {
        std::cout << "p is egual: " << p - 1 << std::endl;
    }   
    else {
        std::cout << "p is negative: " << p << std::endl;
    }

    return 0;
}

I got the output: gcc circonfEn.cc -lstdc++ -o circonfEn ./circonfEn
l is egual: 0 p is egual: 2

Why the instruction in the if do not work?

Upvotes: 1

Views: 71

Answers (3)

HolyBlackCat
HolyBlackCat

Reputation: 96053

Your code essentially means (modulo the scope of l):

int l = ((j * 300) - (4 * n) - (7 * m)) > 0;
if (l != 0) {
    std::cout << "l is egual: " << l - 1 << std::endl;
}   
else {
    std::cout << "l is negative: " << l << std::endl;
}

Since > returns a bool, the value of l is always 0 or 1.

The code should be rewritten as:

int l = (j * 300) - (4 * n) - (7 * m);
if (l > 0) {
    std::cout << "l is egual: " << l - 1 << std::endl;
}   
else {
    std::cout << "l is negative: " << l << std::endl;
}

Or:

if (int l = (j * 300) - (4 * n) - (7 * m); l > 0) {
    std::cout << "l is egual: " << l - 1 << std::endl;
}   
else {
    std::cout << "l is negative: " << l << std::endl;
}

Upvotes: 4

Defining variables in the condition of an if statement is a little known feature. I'm afraid you are not using it as prescribed. You see, when you write:

if (int l = <whatever>)

Then it's the same as if you've written

int l = <whatever>;
if(l)

l itself is evaluated for truthiness. You can't specify it needs to be evaluated as l > 0. So when you write:

int l = ((j * 300) - (4 * n) - (7 * m)) > 0

l will be either 0 or 1. Because you initialize it with ((j * 300) - (4 * n) - (7 * m)) > 0

Upvotes: 2

seunggabi
seunggabi

Reputation: 1822

int l = ((j * 300) - (4 * n) - (7 * m)) > 0 // true;
l = 1; // because true == 1;
1 - 1 = 0; // so, l is egual: 0;

Do you understand?

Upvotes: 2

Related Questions