1

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?

1
  • 1
    It's thé boolean operation that gets into l. You get int l = 2>0 then l=1 Commented Sep 16, 2018 at 8:33

3 Answers 3

4

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Anybody who tries the last solution, make sure your compiler is in C++17 mode.
2
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?

1 Comment

Yes I understand. Thank you.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.