what is the correct syntax for checking a varable value and then setting a varable in the same condition also checking that new set varables var, all in one if statement?
so basically something like
if(this->somevar > 0 && this->newvar = this->GetNewVar(this->somevar),this->newvar > 0)
i know that is not the correct syntax or at least its not working for me anyway, hence the topic, i am using that as an example, so if this->somevar is null or 0, i don't want it to execute the next condition which is && this->newvar = this->GetNewVar(this->somevar,this->newvar but instead skip the statement and ignore that part.
what is the correct syntax for something like this?
&& is an operator with short circuit evaluation, right part is not executed if left part is true.
But why don't you simply write:
if(this->somevar > 0)
{
this->newvar = this->GetNewVar(this->somevar);
if (this->newvar > 0)
{
...
This will certainly makes things clearer ...
the logical AND && operator is short-circuited if this->somevar evaluates to zero, meaning the rest of your if expression would not be evaluated in that situation
The expression after the comma is not necessary. Also, there is one thing missing, parentheses arround the assignment:
if(this->somevar > 0 && (this->newvar = this->GetNewVar(this->somevar)) > 0)
Without the parentheses you may end up setting this->newvar to the value of the boolean expression
this->GetNewVar(this->somevar),this->newvar > 0, which will be evaluated to a boolean result (true/false which, in turn, may be converted to 0 or 1 or -1 depending on the compiler, when cast to the type of this->newvar).
I think only the bit after the comma is evaluated for the if condition. The expression on the left of the comma is ignored.
int main() {
if( false, true) { cout << " got to if( false, true ) "; }
if ( true, false ) { cout << "got to if( true, false ) "; }
}
to answer your question, you can put anything on the left of the comma and do whatever you like, as long as the expression you want to evaluate is the last expression in the list.
so if ( exp1, exp2, exp3 , exp4 ) dowhatever(); only gets run if exp4 is true. You should really run exp1 to exp3 outside the if condition for readability.
Related
In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);
The == operator has a higher priority than the && operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.
You can read about Operator Precedence and Associativity on cppreference.com.
When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:
if( (0 && (a++)) == 0 )
Though, it does not make any sense, as it always evaluates to true and a++ is not incremented here, either.
As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into
if( 0 && ((a++)==0))
However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a
if( ((++a) && 0) == 0 )
Although the question seems easy it's very error-prone.
We need to know the precedence of various operators involved in this.
1. postfix (++)
2. ==
3. Logical AND (&&)
the final expression can be seen as: if ( (0 && (a++)) == 0 )
which is true. Hence statement under if is evaluated to be true.
I cannot understand what it means to evaluate something in c++. I have this sentence: " Its syntax is:
condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2." I know what the point is but I can't really get the meaning of the word "evaluate" straight in this context. Does it mean something like to continue, to check or what?
Thanks! Much appreciated
Every expression has a value. That value is obtained by evaluating the expression. And in some forced contortion of the English language, we sometimes say that "the expression evaluates to [something]".
The evaluation of expressions generally happens at runtime, it is a runtime property of your program. (The exception are constant expressions.)
The rules for evaluation are defined recursive:
A literal evaluates to the value it represents, e.g. 5 evaluates to the value "5".
An expression a + b evaluates to the mathematical sum of the values of the expressions a and b. (So to evaluate the expression a + b, you first have to evaluate the expressions a and b.)
The expression a = b evaluates to the new value of a (and has a side effect, which is to change the value of the lvalue designated by a to the value of b).
... and so on ...
The expression c ? a : b evaluates to the conversion of either a or b, depending on the value of c, to the common type of the types of a and b.
Note that not all expressions are evaluated. For example, in the expression sizeof(+a), neither the subexpression +a nor the subexpression a are evaluated. Similarly, in the conditional expression the unused expression is not evaluated, and in logical expressions, the short-circuited dead expression is not evaluated.
"Undefined behaviour at runtime" is usually a consequence of expression evaluation.
The conditional operator evaluates an expression, returning one value if that expression evaluates to true, and a different one if the expression evaluates as false. Its syntax is:
condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2.
5>3 ? a : b // evaluates to the value of a, since 5 is greater than 3.
a>b ? a : b // evaluates to whichever is greater, a or b.
I can't really get the meaning of the word "evaluate" straight in
this context
it means that the expression has a single value after evaluation . for example in this
7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.
the expression evaluates to 3 (i.e the value of expression is 3)
before evaluation it could have been 4 or 3 but after evaluation the expression equals to 3
It is shorthand syntax of if else. If the condition of the expression (condition) is true result1 will be executed else result2.
It is the short form of if else, Like.
if(condition){
result1;
}else{
result2;
}
Practical example.
int age = 25;
age >= 25 ? cout << "Result 1" : cout << "result 2";
Explanation: If age is greater than or equal to 25, Result 1 else Result 2.
Evaluate means that if you get true from the condition(expression) result1 and if you get false result2.
Firstly, we'll take a complete statement, as the one you have posted is incomplete:
store = condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2
This means that if the expression, which is called condition in your shortened if-statement, is true, then result1 is stored in the variable on the left-hand side of the equation, which is store here.
On the other hand, if conditionis not true, then result2 will be stored in store. That's all what the expression means.
This kind of expression is a shortened if-else statement. If you were to convert this statement into a full if-else statement, then it would look something like:
if (condition == true)
store = result1;
else
store = result2;
Here is an example of this kind of statement:
Suppose we have:
int num = 5;
int var = (num == 5) ? 6 : 10;
Then we can expand this statement to be rewritten with the same meaning as follows:
int num = 5;
int var;
if (num == 5)
var = 6;
else
var = 10;
In both cases here, the resulting expression results in 6 being stored in var.
So in short, evaluates simply means that the resulting expression based on the if-else comparison is evaluated, and the resulting value is passed to the variable on the left. Sometimes, there may not be a variable on the left side, and in that case, the function or expression being "evaluated" will be run. An example like:
(num == 5) ? cout << "result1" : cout << "result2";
Will output result1 in the end.
Also, an example like:
(num == 5) ? cout << 5 + 23 : cout << 4 + 32;
Will evaluate the first expression (since numis initialized to 5 from the previous example) to 28, and then output that.
Hope this helps.
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
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.
string temp is equal to "ZERO:\t.WORD\t1" from my debugger. (the first line of my file)
string temp = RemoveWhiteSpace(data);
int i = 0;
if ( temp.length() > 0 && isalpha(temp[0]) )
cout << "without true worked" << endl;
if ( temp.length() > 0 && isalpha(temp[0]) == true )
cout << "with true worked" << endl;
This is my code to check if first character of temp is a a-z,A-Z. The first if statement will evaluate to true and the 2nd to false. WHY?!?!?! I have tried this even without the "temp.length() > 0 &&" and it still evaluates false. It just hates the "== true". The only thing I can think of is that isalpha() returns != 0 and true == 1. Then, you could get isalpha() == 2 != 1. But, I have no idea if C++ is that ... weird.
BTW, I dont need to know that the "== true" is logically pointless. I know.
output was
without true worked
Compiled with CodeBlock using GNU GCC on Ubuntu 9.10 (if this matters any)
The is* functions are only guaranteed to return a non-zero value if true, NOT necessarily a 1. A typical implementation is table based, with one entry in the table for each character value, and a set of bits defining which bit means what. The is* function will just AND the right bitmask with the table value, and return that, which will only be the value 1 for whichever type happens to have been given bit position 0.
E.g.:
#define __digit 1
#define __lower 2
#define __upper 4
extern int __type_table[];
int isdigit(int c) {
return __type_table[c+1] & __digit;
}
int isalpha(int c) {
return __type_table[c+1] & (__lower | __upper);
}
int islower(int c) {
return __type_table[c+1] & __lower;
}
int isupper(int c) {
return __type_table[c+1] & __upper;
}
Where __type_table is defined as something like int __type_table[UINT_MAX+1]; and would be initialized so (for example) __type_table['0'+1] == __digit and __type_table['A'+1] == __upper.
In case you care, the '+1' part is to leave a spot at the beginning of the table for EOF (which is typically defined as -1).
isalpha doesn't return true, it returns non-zero. This is quite common for API designed for C.
Note that in the expression isalpha(ch) == true, the subexpression true is promoted to type int with value 1.
Well, the documentation suggests that it returns either zero or non-zero, not necessarily just false or true. So you'd better check (isalpha(temp[0]) != 0).
Do not isalpha(ch) == true, but !!isalpha(ch) == true