C++ code printing strange values [duplicate] - c++

This question already has answers here:
Math-like chaining of the comparison operator - as in, "if ( (5<j<=1) )" [duplicate]
(4 answers)
Closed 8 years ago.
i am having a very silly but strange problem. When i am trying to compile and run the following code my compiler is printing "ggl" but i think it shouldn't. It is strange that after doing so much programming i am stuck here. What exactly is the problem? Can someone please help me out? Thanks in advance !!
#include <iostream>
using namespace std;
int main() {
int t=8;
if(1<t<5){
cout<<"ggl";
}
//cout<<aa;
return 0;
}

This line doesn't do what you think it does
if(1<t<5)
You would have to say
if (1 < t && t < 5)
The first version says
if ((1 < t) < 5)
Which evaluates to
if (true < 5)
if (1 < 5)
Which is always true.

Your if condition effectively says if ((1 < t) < 5), which is always true, because (1 < t) is either 1 or 0 (1 < 8 evaluates to 1).
Since chained comparisons do not (usually) work in C++, you'll need to check the condition differently:
if (1 < t && t < 5) {
cout << "ggl";
}

This
if(1<t<5)
does not do what you think it does. It does not determine whether t is between 1 and 5. You want
if ((1<t) && (t<5))
What it actually does is take the value (1<t) (which will 1 if 1<t and 0 otherwise), then see if that value is less than 5, which it always will be.

Related

why does the output change when i change z -1 to z--? [duplicate]

This question already has answers here:
Pre vs Post Increment
(3 answers)
Closed 8 months ago.
I have the following c++ program:
#include <iostream>
using namespace std;
//looping through arrays backwards
int main() {
int a[3] {1, 2, 3};
int x = sizeof(a), y = sizeof(int), z = x / y;
for(int i = z - 1; i >= 0; i--) {
cout << a[i] << " ";
}
return 0;
}
And it outputs 3 2 1. But if I change the first parameter in the for loop to int i = z--;, it outpus 2 3 2 1 and I don't understand why. Aren't z - 1 and z-- supposed to be the same thing? Could someone please explain why? Also, I'm a begginer in C++ and I'm learning via the W3Schools tutorial about it. Thanks!
The expression z-- evaluates to z, then - as a side effect - z is decremented (scheduled according to scheduling rules). This means, you're essentially saying int i = z in your loop (and then decrement z, but it's not used anymore) - therefore, your code has UB. The 2 printed is purely coincidental, anything might be printed or anything could happen in your code. If you'd like to use --, use it as prefix, i. e., int i = --z.

C++ problems with division [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 2 years ago.
Improve this question
I need to make a program in C++ in which I insert a number 'n' that's with 4 digits and it's a simple number, in the console and the console is showing me the multiplication of the certain number with 4 digits which I first needed to write.
I tried to write (n/!2) in order to make the program execute only if the number can't divide by 2 and the console showed "main.cpp:22:36: warning: division by zero [-Wdiv-by-zero]".
I've tried removing
(n /! 2) and the code got executed without a problem. I will be glad if someone can tell me how can I fix it.
#include <bits/stdc++.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int getProduct(int n)
{
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
return product;
}
int main()
{
int n;
cout << "insert n ";
cin >> n;
if (n >= 1000 && n <= 9999 && n /! 2) {
cout << (getProduct(n));
}
}
In the calculation n / !2 You effectively do n / 0.
! is short for not, not 2 is a boolean expression where 2 (anything but 0) is true.
not true is false.
false is promoted to an int in the calculation and false there becomes 0.
Solution: Use n % 2 != 0 or n & 1 to check for odd numbers.
You are looking for modulo operation. Modulo (the remainder from division) is equal to zero if number is divisible by the other one and non-zero otherwise.
if (n >=1000 && n <= 9999 && (n % 2) != 0)
tried to write (n/!2) in order to make the program execute only if the number can't divide by 2
n / !2
This evaluates to n / 0. which triggers your warning.
To check if n is odd, you should do this instead:
n % 2 != 0
! operator have higher precedence than / , So your expression becomes
=> n/(!2)
=> n/0
Instead you shoud use (n%2==0) to check for even number.

Why can't we do three-way comparison in C++? [duplicate]

This question already has answers here:
Comparing a variable to a range of values
(7 answers)
Closed 3 years ago.
To summarize it quickly, why isn't 2 < x < 9 equal to 2 < x && x < 9?
This is the test code I've written:
#include <iostream>
int main()
{
int nums[] = { 5 , 1, 10};
// We are gonna check if the number is in the range 2 - 9
for (auto e : nums)
{
if (2 < e < 9)
std::cout << "2 < " << e << " < 9" << std::endl;
if(2 < e && e < 9)
std::cout << "2 < " << e << " and " << e << " < 9" << std::endl;
}
std::cin.get();
}
Here is the output I'm getting:
2 < 5 < 9
2 < 5 and 5 < 9
2 < 1 < 9
2 < 10 < 9
It looks like only 2 < e && e < 9 works correctly.
The expression
2 < x < 9
is grouped as
(2 < x) < 9
And since 2 < x is either false (0) or true (1), and both are less than 9, it's always true.
So unless you use overloaded operators for a non-built-in type x (then a 3-way comparison would be possible if 2 < x were to return an instance of a proxy object on which < is defined), if you want to test if x is in the interval (2, 9) you need to write it the way you have.
Just because this language doesn't have that feature.
It could have been made to, but this would contrast with C in a non-compatible way.
C could have been made to, but the designers simply didn't do that.
You already have the correct way to do it.
Some different (and newer!) languages do support this.
the comparison operators in c++ takes as an argument two values.
when you are writing a<b it is the same as operator<(a,b).
and the return value of operator< is bool.
when you are calling a function in c++, it is computing the expression of its arguments and then passing it to that function, so calling a<b<c is same as
operator<(operator<(a,b),c)
basically, the answer to your question is that in c++ there is no comparison operator (less than, greater than...) that takes three arguments
If C++ chose to redefine a < b < c to better align with the mathematical notation, it would be ambiguous with the current meaning. The current meaning is a bit silly and is comparing bools with numbers, but there may be tricky code relying on this detail in production use.
And as C++ allows you to define your own types with operators, it would have to expose the new ternary < to you as well, so you could make one for your type. Which would open new cans of worms if you only define a binary < but no ternary < for your type - should the compiler start shouting at you?
C++ didn’t do it because that would have broken backward compatibility with C. So you would need to look another decade back for the answer.
I don’t know whether Brian Kernighan or Dennis Ritchie ever considered doing it the other way, or discussed their reasoning. I’m not aware of anyone requesting that specific feature. Their relational operators follow the same rules as other Algol-family languages.
One problem would have been that it makes the grammar ambiguous: 0 < x < 1 now has a very different meaning than (0 < x) < 1 or 0 < (x < 1). There are also the issue of how to parse a < b >= c or a < b == c. Remember, there was no Boolean type in K&R C. Logical operators returned int, since the result was presumed to be stored in a machine register.
Another possible reason behind it is that K&R C, according to its designers, is not a high-level language. Its basic operations generally correspond to machine instructions on the minicomputers it was developed on. So, a comparison was a machine instruction back then, and a double-comparison was not. It would’ve been strange, given the other choices they made, to introduce that particular syntactic sugar into the language just to make C code read a little more like a math paper.
Inside of if, there should be boolean condition. In 2 < x < 9, there are two conditions. And two conditions can't be calculated in C++ without operator between them. That's why we can't use 2 < x < 9.

Can not understand working of a line [duplicate]

This question already has answers here:
How do I use the conditional (ternary) operator?
(10 answers)
What does the question mark character ('?') mean in C++?
(8 answers)
Closed 6 years ago.
I took few help online to complete my task. And I found this code but I do not know the actual working as I have never used such syntax before in c++. The (?) Question mark and (:) colon.Can any one provide a simple general syntax code explaining same line?
x = (i-coins[j] >= 0)? table[i - coins[j]][j]: 0;
This means
if (i-coins[j] >= 0)
x = table[i - coins[j]][j];
else
x = 0;
This is called ternary operator, and it is used in place for a short if-else statement.
int factorial(int number) {
if (number < 1) {
return 1;
} else {
return number*(number-1);
}
}
The above function can be summed up using a ternary operator:
int factorial(int number) {
return (number < 1) ? 1 : number*(number-1);
}

Is there any faster way to check if a number is a integral power of 2 in c++ [duplicate]

This question already has answers here:
How to check if a number is a power of 2
(32 answers)
Closed 7 years ago.
I know this method and it is not efficient enough
(a/2)%2==0;
See the Bit Twiddling Hacks :
unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));
Your method does not check that. It will return true for 12 for example.(and will return false for 2)
To check you may use x != 0 && (x & (x - 1)) == 0
If you're using gcc and x64 there's an intrinsic that lets you use the CPU instruction that counts bits:
int __builtin_popcount (unsigned int x)