Is this explanation of ternary operator valid? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Question:
I want to know if this explanation of the ternary operator is valid.
var = (condition) ? set value if condition one : set value of condition two;
If the condition is something than the value of the variable will be something. If it's not the value will be different. Basically assign a variable with a value based on a condition. Is this explanation valid? I need to know this if I'm understanding this correctly.
Code:
#include <iostream>
bool maxEntries()
{
int entries = 11;
bool users = (entries > 10) ? true : false;
return users;
}
int main(int argc, const char* argv[])
{
if(maxEntries())
{
std::cout << "Entries are greater than 10." << std::endl;
} else {
std::cout << "Entries are less than 10." << std::endl;
}
return 0;
}
.

I want to know if this explanation of the ternary operator is valid.
That explanation is not for ternary operator, but for expression that assigns to a variable result of ternary operator. Ternary operator itself is more than that:
int a = 0, b = 0;
condition ? a = 1 : b = 2; // based on condition assign 1 to a or 2 to b
( condition ? a : b ) = 100; // based on condition assign 100 to a or b
in your case
condition ? value1 : value2; // result of ternary operator either value1 or value2 based on condition
you then use the result to assign to a variable, so your explanation is not for ternary operator but for whole expression that uses ternary:
var = condition ? value1 : value2;
you may think this is neat picking but if somebody would read your explanation he may think that assignment to a variable is part of the ternary operator itself, but that is not the case. For example:
function_call( condition ? value_on_true : value_on_false );
Also this at least confusing: "If the condition is something" it should be "if the condition is true then first otherwise (condition is false) the second.

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.

what is the the purpose of using ? and : in the following code [duplicate]

This question already has answers here:
What does the question mark character ('?') mean in C++?
(8 answers)
Closed 1 year ago.
I am a complete beginner in C++. i recently came across a piece of code. I don't seem to understand the use of ? and :. can anyone tell me how it works? why we use ? and :
CODE
(j==1 or i==s)?(cout<<"* "):((j==i)?(cout<<" *"):(cout<<" "));
It is a ternary operator. The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
Syntax:
The conditional operator is of the form.
variable = Expression1 ? Expression2 : Expression3
It can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Ternary operator
A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.
Its syntax is:
condition ? expression1 : expression2;
Here, condition is evaluated and
if condition is true, expression1 is executed.
And, if condition is false, expression2 is executed.
You can find a example here https://www.programiz.com/cpp-programming/ternary-operator
It is a short circuit test condition if/else, then put the assign value.
void Main()
{
// ****** Example 1: if/else
string result = "";
int age = 10;
if(age > 18)
{
result = "You can start college";
} else
{
result = "You are not ready for college";
}
// ****** Example 2: if/else with short circuit test condition
result = (age > 18) ? "You can start college" : "You are not ready for college";
}

Can someone please explain the output to me? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
okay, so when i change the " = " in if( (i = 4) || (i = 5) ) to "==" it returns hello world. But when the "=" is kept at "=" the output is nothing. It does not give me a syntax error cuz ik you need to put "==" inside an if
void f( int i )
{
if( (i = 4) || (i = 5) ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So when the code is "if( (i = 4) || (i = 5) )" output is nothing (as in the screen is empty).
when the code is "if( (i == 4) || (i == 5) )" output is hello world.
my main question is: Why does == and = make a difference in the output but not give me a syntax error?
As #Carcigenicate said, == and = is different.
== is for comparing and = is for assigning.
An assignment a = b does not only set the value in variable a to b, but also returns the value of b. This way, an assignment like a = b = c is possible, because the value returned to be put in a is the same as has been set to b. You can use this trick in conditionals, as you've done, for example:
int x;
while(x = functionWhichCouldReturnZero()){
// Do something with x
}
When C++ tries to interpret the return value as a boolean (true or false), it interprets 0 as false, and all other values as true.
On the other hand, with (a == b), this is a pure conditional, and returns true if a is equal to b, otherwise it returns false.

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.

Confusing outcome of C conditional operator [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int a=1,b=2,c=3;
int x=1;
int y=10;
a = x ? b : c;
cout<< a; // Outputs 2 (the value of b)
a = y ? b : c;
cout<< a; // Outputs 2 (the value of b)
Now, look at the following.
a=0;
x=0;
a = x ? b : c;
cout<< a; // Outputs 3 (the value of c !!!!)
Why this unusual behaviour ?? Only when a and x are both 0, the expression evaluates to false , otherwise, always it is true. Please explain.
Because x is 0.
Recall that the ternary operator, if written condition ? a : b returns a if condition is true and b otherwise. You are using it with numbers, and any number except 0 is considered true as a boolean.
x ? b : c in your case is 0 ? 2 : 3, and since 0 is false, it evaluates to 3. That 3 then gets assigned to your a variable and printed - nothing unusual going on here.
This looks perfectly fine. The expression a = x ? b : c is equivalent to
if (x)
a = b;
else
a = c;
x will evaluate to true for any nonzero value, so if you assign 0 to x prior to executing the expression, the value of c will be assigned to a, and if you assign 1 to x prior to executing the expression, the value of b will be assigned to a. The prior value of a is immaterial here.
The reason is that in C and C++ any non-zero value is evaluated as "true".
The value of 'a' only depends on the value of 'x' and 'y'. Since initially 'x' and 'y' are both greater than 0, the condition evaluates to true and you get the value of 'b' in 'a'.
In the second case, 'x' is zero which evaluates the condition to false which causes 'a' to have the value of 'c'.
a = x ? b : c;
is the same as
if(x != 0) {
a = b;
} else {
a = c;
}
Therefore if you set x = 0 you will get a = c.