condition in for loop with if operator [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
basically I have this function repeat I understand what it does, what I don't understand is the this part of the condition in the for loop v ? sizeof(g) / 8 : 0, if someone could explain it me I would appreciate a lot because I don't get what it does.
program:
char g[1024];
double *repeat(double *v) {
for (int i = 0; i < (v ? sizeof(g) / 8 : 0); i++)
{
if (v[i] > 2 * i)
v[i] = i;
else
v[i] = 0;
}
return v;
}
int main()
{
double *t;
*t = 2.0;
t = repeat(t);
printf("Numero: %f\n",*t);
return 0;
}

This is somewhat obscure code, as illustrated by the number of incorrect attempts at answers. The key here is that the ?: operator makes an expression, that is, it's code that produces a value. So, first look at the value of the expression:
(v ? sizeof(g) / 8 : 0)
where v is a pointer. When a pointer is used in a context that expects a boolean value, the value is true if the pointer is not a null pointer, and false if it is. So, you could think of this expression as
(v != nullptr ? sizeof(g) / 8 : 0)
This expression is the upper bound of the for loop. The loop will execute for as long as i < (v ? sizeof(g) / 8 : 0) is true. So, if v is a null pointer, the condition is i < 0, which is false, and the body of the loop will not be run. If v is not a null pointer, the condition is i < sizeof(g)/8, and the body of the loop will be run as many times as whatever that value is.

If v is true, then sizeof(g) / 8 gets executed. If v is false, then 0 gets executed

If the input parameter v is not NULL, then we compare i to the result of sizeof(g) / 8 (64 in this particular case); otherwise we compare i to 0.
The following code would be equivalent (and probably a little easier to understand):
int count = 0;
if ( v )
count = sizeof g / 8;
for ( int i = 1; i < count; i++ ) { ... }

Since you say in a comment you are confused because v is a pointer, not a boolean — and yet is used in a condition:
Since the beginning of C++ there is a well-defined automatic conversion of pointers to booleans which is defined exactly for this use case of testing whether a pointer is null instead of the wordy if(p != 0 ). The latter is more complicated hence more error prone:
OK, we compare against a null pointer (in C++ a literal zero was the only null pointer literal before the introduction of nullptr).
OK, we test for inequality.
OK, two negations (null pointer and inequality) make for a positive: Is the pointer there? I think that's what it is. I'm tired. Let's be sure and play it through in our minds. I have a valid pointer. It is not equal to 0. Inequality therefore returns false. The false result indicates it's a valid pointer. I think this is what I wanted, right? Where was I?
Instead , you simply write if(p). no comparison, no double logic inversion, it couldn't be simpler: If the pointer is there, do something with it ;-).

i < (v ? sizeof(g) / 8 : 0)
This is the equivalent of saying this shorthand:
if(v){
i < sizeof(g)/8;
}else{
i < 0;
}

Related

Why does == work and = does not in an if statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
for (unsigned int i = 0; i < list.size(); i++) {
if (list.at(i) = n) {
cout << "True";
return 0;
}}
I was wondering why this would not work I understand that tou should use list.at(i) == n.
However i thought that a single = means assigning, and a double == means equal to. I understand it is different but wouldn't using only one = still be correct when using it in an if statement?
It would not necessarily be correct. When you use an assignment expression as a boolean for integers, it will return true if the integer is not zero, and it will return false if the integer is zero.
Suppose our list looks like this: 1, 2, 0, 5. Now, suppose we have this if-statement:
if (list.at(0) = 1) {
cout << "True";
}
Since the 1 in list.at(0) = 1 is not 0, the if-condition will be satisfied. If we used ==, it would be satisfied since the first value is indeed 1.
Now let's suppose we have this if-statement:
if (list.at(1) = 3) {
cout << "True";
}
The "True" would be printed because 3 is not equal to 0. However, if we replaced = with ==, the "True" would not be printed since the second value is not 3.
Let's look at one last example.
if (list.at(2) = 0) {
cout << "True";
}
This would not print out "True" since we are assigning list.at(2) to 0. However, if we replaced the = with ==, the "True" would be printed since the third value in the list is actually 0.
This shows that = cannot be used as ==.
P.S. And, if you wanted to use the list later, your list would be modified into a different list.
if (condition) {
// block of code to be executed if the condition is true
}
Here is your code list.at(i) = n is an assignment and not a condition. Seeing your code I can say that you want to check if any value in the list is equal to n or not if it is then you want to print True.
So to do this you have to use a condition if(list.at(i)==n).
For more information read about condition statements, comparison operators, and assignment operators.

terminate called after throwing an instance of 'std::out_of_range' and I don't know how to solve it [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have been working to code, a calculator, that works with recursion.
Input: ! + 1 3
code will do 1+3 and then take the faculity of the sum
output: "24"
I finished writing the basic code( not having filtered out wrong user-input yet),
when I build it shows no warnings, but once I run it I get thrown with the 'std::out_of_range' warning. I tried around and nailed the problem down to one function, but I am unable to identify whats wrong exactly.
//Calculation
string Rechner::berechne(vector <string> t) //Calculator::calculate
{
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
if( t.at(i) == "+" || t.at(i) == "*" || t.at(i) == "!") //finds the last operator
{
t.at(i) = differenziere(i, t); //switches out the last operator with
//the result of the operation (differenziere(i, t)
if ( t.at(i) == "!")
{
t.pop_back(); // delets last element of vector and
berechne(t); // searches for the next Operator
}
else
{
t.pop_back(); //delets last two elements
t.pop_back();
berechne(t); //searches for next operator
}
}
}
return t.at(0); //when there is no more operator left, this returns the Result of the whole operation
}
For example
input: 5
the output should be 5, because there is no more operator, but i get the out_of_range warning.
input: + 1 3
has the same output of the warning.
So my best guess is, once the vector consists out of one string, for some reason this falls into the if function, what doesn't make sense to me.
Input is a string, that I convert to a vector. This works all fine, i have tested that.
I am working with code::blocks, c++11 and on a windows laptop.
I hope you can help me.
Also please excuse my english, it's not my native language. I speak fluet normally, but I haven't been around the topic of coding for long, so this is s a little different for me.
i >= 0 will be always true because i is unsigned.
Instead of this
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
You can do
for (unsigned int i_loop = t.size(); i_loop > 0; i_loop--) //searches the vector starting from the back
{
unsigned int i = i_loop - 1; // i_loop is positive here thanks to the loop condition

What happens due to & operator in the following case?

I have known, '&' as bitwise and as an operator to get memory address of a variable.
What happens in this case of the code?
res = res & (a[i]<[a[i+1]]);
If it is bitwise and , as far as I know the second condition is also checked,
but what if I used logical and instead of it , wouldn't it still be the same?
As first part is (say) false , second parts get checked comes true, but still res remains false.
Would it be same (for this case) to use logical and for this? or it has some other use (& operator) for this case?
int a[] {1,3,4,2};
int pos = 3;
bool res = true;
for(int i = 0; i < pos; i++)
res &= (a[i] < a[i + 1]);
(Sorry for bad english)
If it is bitwise and , as far as I know the second condition is also checked, but what if I used logical and instead of it , wouldn't it still be the same?
No. Boolean and (written as && or and) has short circuit evaluation - if left part is false right part is not evaluated at all. This allows to write code like this:
if( pointer != nullptr && pointer->value > 100 ) ...
if not short circuit evaluation this code would have UB. For example this code:
if( pointer != nullptr & pointer->value > 100 ) ...
has Undefined Behaviour when pointer is equal to nullptr
Would it be same (for this case) to use logical and for this? or it has some other use (& operator) for this case?
You cannot, as there is no &&= operator in C++. You can write:
res = res && (a[i] < a[i + 1]);
and that would have short circuit as well and compiler may even be smart enough to stop the loop, though I doubt and it should be expressed explicitly anyway:
bool res = true;
for(int i = 0; res && i < pos; i++)
res = a[i] < a[i + 1];
which does the same, but cleaner and more efficient.
Anyway when you need logical or boolean and you should use one to make your intention clear and avoid unexpected surprises.
Besides the short circuiting issue, If res == 2 then:
res & 1 will return 0 which will be interpreted as false.
res && 1 will return true.
Your question is not clear.
Okay, let's dive into your code.
Your given code is very clear. You are performing bitwise and for pos(3) times. For every loop you are comparing a[i] with a[i+1]. Please note that for the last loop, I mean when variable i becomes 3, then i+1 will be 4. And your array a[] doesn't have a[4]. It only has the last element having index 3.
So for bitwise and operation the value of res isn't predictable as a[4] isn't defined.
Now let's think about logical AND operation. For logical and your expression inside the for loop will once generate a false boolean value for a[i] < a[i+1] as your array a[] = {1,3,4,2}. Here 4>2 not 4<2. Hence it will generate false boolean value and your entire response will be false 'cause you know logical AND will be eventually 0 if one of the operands is false.
I think you have got this.

Mathematic equation solved recursively in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a task to make a code which will write 100 first numbers of an equation (or a function, I don't know what this is)
A(n) = (A(n-1))^2 -n*A(n-2) where A(1) = 1 and A(2) = 1
It has to be solved recursively. I have written this code so far
#include <iostream>
using namespace std;
int rekurzija(int n){
if(n=1){
return 1;
}
if(n=2){
return 1;
}
if(n>2){
return rekurzija(n-1)*rekurzija(n-1)-n*rekurzija(n-2);
}
}
int main(){
for(int n=1;n<101;n=n+1){
cout << rekurzija(n) << endl;
}
}
The problem is that the program returns 1 hundred times instead of 1,1,-2,0,...(instead of actually solving this function). What is wrong in this code?
You are using simple assignment operator = instead of Is equals to relational operator == in your rekurzija() function for if conditions
if(n = 1) //here `n = 1`is an assignment statement
{
//something...
}
What happens if you use = instead of ==?
The if condition will always evaluate to be true if the assigned value in the assignment statement is non-zero number.
Note: An assignment to zero evaluates to be false i.e, for if(n = 0), the if block will not be entered. You don't have any such if blocks in your code.
So your first if is always evaluated to be true because you are assigning a non-zero value i.e, 1 and thus your function always returns 1. that's the reason why you get 100 1's as your answer.
So, instead try changing all the if conditions to something like:
if(n == 1)
{
//something...
}
This would check if n is equals to 1 or not. If n is equal to 1 then the if block is entered, else it would not enter the if block and the next if condition is checked.
Note: Just remember this while using the = and == operators
= is for assignment
== is for comparison
When you compare things in C++ you need to do it like:
if (a == b)
and not
if (a = b)
The latter will assign b to a and return the value of a.

Integer to Boolean strange syntax [duplicate]

This question already has an answer here:
The Definitive C++ Book Guide and List
(1 answer)
Closed 7 years ago.
I'm less than a year into C++ development (focused on other languages prior to this) and I'm looking at a guy's code who's been doing this for two decades. I've never seen this syntax before and hopefully someone can be of some help.
bool b; // There exists a Boolean variable.
int i; // There exists an integer variable.
sscanf(value, "%d", &i); // The int is assigned from a scan.
b = (i != 0); // I have never seen this syntax before.
I get that the boolean is being assigned from the int that was just scanned, but I don't get the (* != 0) aspects of what's going on. Could someone explain why this person who knows the language much better than I is doing syntax like this?
Have a read here:
http://en.cppreference.com/w/cpp/language/operator_comparison
The result of operator != is a bool. So the person is saying "compare the value in i with 0". If 'i' is not equal to 0, then the '!=' returns true.
So in effect the value in b is "true if 'i' is anything but zero"
EDIT: In response to the OP's comment on this, yes you could have a similar situation if you used any other operator which returns bool. Of course when used with an int type, the != means negative numbers evaluate to true. If > 0 were used then both 0 and negative numbers would evaluate to false.
The expression (i != 0) evaluates to a boolean value, true if the expression is true (i.e. if i is non-zero) and false otherwise.
This value is then assigned to b.
You'd get the same result from b = i;, if you prefer brevity to explicitness, due to the standard boolean conversion from numeric types which gives false for zero and true for non-zero.
Or b = (i != 0) ? true : false; if you like extraneous verbosity.
(i != 0) is an expression that evaluates to true or false. Hence, b gets the value of true/false depending on the value of i.
This is fairly fundamental syntax. The != operator performs a "not equal to" comparison.
You may be being confused by the shorthand of initialising a bool directly from the result of a comparison operator, but the syntax itself is not esoteric.
The program is essentially equivalent to:
bool b;
int i;
sscanf(value, "%d", &i);
if (i != 0)
b = true;
else
b = false;
The key is that i != 0 is itself an expression that evaluates to true or false, not some magic that may only be used in an if statement.
Basically, if the condition (i not_equal_to 0 ) is satisfied, b gets the value "true". Else b gets the value "false".
Here, "i != 0" is a boolean expression that will be true if "i" is non-zero and false if it is zero.
All that is happening here is the result of that expression is being assigned to a variable.
You could also do things like...
boolean canDrinkAlcohol = (person.age() >= 18 && person.country.equals("UK") || person.age() >= 21 && person.county.equals("US"));
...
if(canDrinkAlcohol) {
...
}
or something