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 6 years ago.
Improve this question
For the below sample code:
// Note that a, b, c and d can have value of 0 or 1 only
int isAllTrue(int a, int b, int c, int d)
{
return (a && b && c && d);
// THIS ALSO RETURNS CORRECT VALUE
// return (a & b & c & d);
}
If we know that operands can be either 0 or 1, which operation would be preferable from performance point of view: bitwise or logical? Does it really matter?
Does evaluation stop in the case of bitwise "&" when the operand is 0 ?
Use & for bit operations. Use && for logical operations. If you use a bitwise operation where you should use a logical operation or vice versa, the reader will (a) be confused, (b) check very carefully if your code has introduced a subtle bug.
Programming relies on idioms. If your code doesn't match the expected idiom, then you must have a good reason, and you should write a comment explaining why.
It doesn't matter which formulation you use, with active compiler optimization, all shown evaluations should already be completed at compile time.
As for your last question, the bitwise operators do not employ shortcut evaluation and thus always evaluate each operand.
there seems to be a lot of confusion about questions like this one ... and a lot of wrong answers. Well, here are the facts for C/C++ :
&&, || and ! are logical operators, they test for
boolean expressions - integral values (numbers) are considered true if their value is not zero, false otherwise -
no matter how many numbers you check for but 0 && 1 will be evaluated to false, for instance because of the first 0 -- it could be re-written as false && true
&, |, ~, ^, >>, << are bitwise operators, they mask/assign
bit patterns of integral values, you can do a lot of cool calculations like that - but you really need to know how numbers are represented inside of your CPU before you start doing that.
Conclusion : your question doesnt make sense - because you thought that these operators are similar .... they arent.
Related
What is the output of the following program, and why?
#include<stdio.h>
#include<conio.h>
int main()
{
int a=5;
a +=a += a += 2;
printf("%d",a);
getch();
return 0;
}
The behaviour of your program is undefined as you are reading from and writing to a in an unsequenced step.
What your ancient compiler is doing is correctly following the C grammar rules and is grouping the expression as
a += (a += (a += 2))
But grouping is not the same as sequencing. From this point the behaviour is undefined. Your compiler appears to evaluate the above to
a += (a += 7)
followed by
a += 14
to yield 28.
This is a tough question without an easy, obvious answer.
The expression is probably undefined, in which case it's meaningless to ask "what could be the possible output?", because it could be anything.
If it's undefined, it's because there are multiple writes (stores) to a without any intervening sequence points. The rightmost a += 2 computes 7 and prepares to store it into a. Next we have the middle a +=, which tries to take the 7 and add it to... what? The old or the new value of a? If it's the old we compute 5+7= 12 and if it's the new we compute 7+7=14, and whichever value we compute, we prepare to store it into a, but does it "win" and overwrite the value that the rightmost a += 2 tried to store, or not? And then the arguments (and the multiplicity of different interpretations and possible answers) proliferate for the leftmost a +=.
Not all assignment expressions are undefined, of course. For example, the old standby
a = a + 1
is well-defined. It both fetches from a and assigns to a, but in this case we don't have to ask, "what if it assigns to a before it fetches from it?", because obviously, it has to fetch from a first, in the process of computing the new value to be assigned. But this argument doesn't rescue a += a += 2, I don't think.
There are newer rules about "sequencing" which do away with the old concept of "sequence points", and the new rules might render this expression well-defined, but I'm not sure.
Unless you're interested in frustrating, head-banging puzzles, it's best to steer clear of expressions like this one. You obviously wouldn't have any use for an expression like this in a real program. It's nearly impossible to figure out (a) if the expression is well-defined and (b) if so, what it's supposed to do, so a program containing an expression like this is unmaintainable; you have to be a hard-core language lawyer to properly understand it.
Naturally it's important to understand how simpler, saner expressions like a += 2 or x += y[i++] work. But for something insane like a += a += a += 2, don't fall into the trap of asking "Wouldn't it help me understand C better if I understand what it means?", because the only thing to understand is that it's borderline, if not absolutely, meaningless.
See also SO's canonical entry on undefined expressions, Why are these constructs (using ++) undefined behavior in C? (although none of the answers there cover this particular case).
It depends on the compiler ! But theoretically 28 is the answer !
The assignment will be from right to left so a +=a += a += 2; can be break down as
5+2=7 a+=2
7+7=14 a+=a+=2
14+14=28 a+=a+=a+=2
Only 3 days while learning C. Noticed this in the book:
int main() {
int x = 10, y = 15;
if (x % 2 == y % 3) {
printf("Which one x%2 or y%3 calculated first");
}
}
My question is in if condition. Question is which expression is calculated first, x%3 or y%3?
The short answer is: C does not specify which of x % 2 and y % 3 is computed first, and since there is no side effect in either sub-expression, it does not matter.
The long answer is: Actually, looking at the generated code on Godbolt Compiler Explorer, the expression may be evaluated at compile time and none of these are computed at runtime.
Very few C operators have a specified order of evaluation:
the comma operator ,
the logical and && and logical or || as well as the ternary operator ? : (they actually only evaluate their second or third operand if the first has a specific truth value).
function arguments are evaluated before the function is called, but their relative order of evaluation is unspecified.
I is a tricky question and it was very popular during the interviews some time ago.
If I make it this example a bit less trivial and avoid optimisations:
int comapare(int x, int y) {
int result;
if (result = (x % 2 == y % 3)) {
printf("Which one x%%2 or y%%3 calculated first");
}
return result;
}
The order of evaluation of this particular is undetermined as only logical operators are guaranteed from the left to the right and evaluate the smallest number of operands needed to determine the result of the expression. Operator == along with all other comparison operators is not the logical operator.
Most interviewed candidates answered that it will be evaluated from the left to the right as it is the logical operation.
It's a good question Gaurav. Always have that inquisitive mind as that's how you can attain true learning.
As suggested in the comments, this question relates to Operator Precedence and Associativity.
Here you can get an idea in general.
Here, it's more specific to your question. As you can see there (point# 3), for % operator, it is from Left-to-right.
It is important to distinguish here between how equality == works versus the assignment operator = as the later works from right-to-left. As mentioned in that link, for the assignment operators like =, the expression a=b=c is parsed as a=(b=c), and not as (a=b)=c because of right-to-left associativity.
Hope this will clear your doubts!
Additional clarifications:
Based on subsequent discussions in the comment section, I feel it necessary to remove some of the confusions.
Confusion about operator associativity and order of evaluation:
If two operators are of same precedence, Associativity of operators determines the order in which they execute. The associativity of == is left to right, i.e, the expression on the left is executed first and moves toward the right. So answer to the question of which expression is calculated first in the equation x % 2 == y % 3, the answer would be like this:
1. evaluation of x % 2.
2. evaluation of y % 3.
3. evaluation of ==
Do compilers strictly follow this rule?
Not necessarily. The compilers are free to evaluate such expressions in any order, if they can guarantee a consistent result. Only the sequential-evaluation (,), logical-AND (&&), logical-OR (||), conditional-expression (? :), and function-call operators constitute sequence points and therefore guarantee a particular order of evaluation for their operands.
Authentic reference: https://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx
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 6 years ago.
Improve this question
Why can we use only four operators (+, -, ++, --) in pointer arithmetic? Does it have any relation with inbuilt hardware since it is dealing with addresses?
Since an array uses relative addressing, in that we increment the address to perform that operation, I think this might be one of the reasons for using those 4 operators alone.
Why can we use only four operators (+, -, ++, --) in pointer arithmetic?
Because the language was built that way. The most common operation is iteration, which is probably why those operators are allowed.
As for rationales behind why the C language was designed this way, there's not much to be found. I checked the C99 rationale regarding pointer arithmetic, but it is mostly concerned about the result of pointer arithmetic overflowing and does not mention why/when pointer arithmetic makes sense.
Does it have any relation with inbuilt hardware since it is dealing with addresses?
No, it has nothing to do with that. Addresses are just numbers. You can always cast any pointer to uintptr_t and then use it as any other integer.
You can use any operator, as long as the result will be int. For example:
int A[10], i=5;
int *p;
p = A + (i/2);
Simple because C was designed that way.
+,- can be simply used to add or subtract two pointers respectively (value at address only). While on the other hand increment and decrement operators i.e ++ and -- can be used to increment or decrement the pointer.Remember the data type of pointer plays an important role in these two(++,--) operators.
For example if you define an pointer of type *int then ++ will increment the memory address by 2 (since the size of int in most compilers is 2 ) and so same is with the -- operator as it will decrease it by a 2.
This question already has answers here:
What are bitwise operators?
(9 answers)
C language What this code mean ? if(button & 1)==1 [closed]
(4 answers)
Closed 8 years ago.
I am looking at the c code:
if((VAR_ON&3) > 1)
I am not sure what kind of variable VAR_ON is, my guess is it is a pointer, but what does the &3 at the end do to it? I apologize if this is a duplicate question, I just could not find any question regarding the ampersand AFTER a variable.
As used in the question code, the ampersand '&' is a bitwise 'and' operation.
Example (assuming that VAR_ON = '21'):
VAR_ON 21(Decimal) 00010101(Binary)
& 3(Decimal) & 00000011(Binary)
------------ ------------------
1(Decimal) 00000001(Binary)
Hence if VAR_ON is '21', the expression (VAR_ON&3) will evaluate to '1'. The 'if' condition would be false:
if((VAR_ON&3) > 1)
& in that context will perform a bit wise AND operation.
So whatever VAR_ON is will be ANDed with 3 so that only the last 2 bits of the variable will be used in the comparison.
It's a bitwise AND. That's not an ampersand "after a variable". That's a bitwise binary operator working on two operands: VAR_ON and 3.
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
I am examining a C code for a pressed key in a embedded system.
In the code below you can see an if-statement with ! before checking REG8, what does this mean in a situation like this? I am just asking about the character (!) and not what the code does.
if(!(REG8(DataRegA) & 0x80)){
*key=REG8(DataRegA) & 0x0F;
return(1);
}
that means the button is active on low better known as active low
That code checks the state of the 7th bit in that register; if it's off, it executes the block of code.
REG8(DataRegA) presumably gets the value of some MCU register, which probably reflects the state of some input signal;
REG8(DataRegA) & 0x80 performs a bitwise AND with 0x80, which returns 0 if the seventh bit is not set, 0x80 otherwise;
the ! is the logical negation operator; in !(REG8(DataRegA) & 0x80) it negates the expression above, i.e. if it's 0 it becomes 1, if it's nonzero it becomes 0.
Thus, the if body is executed only if the 7th bit in the register is not set.
The ! operator yields 0 if its operand is nonzero and 1 if its operand is 0, and the if-statement executes its body if the condition is nonzero. So if REG8(DataRegA) & 0x80 evaluates to 0 (which would make the code in the if-statement's block not execute), the ! operator will reverse it and make it execute.
! is the boolean not operator. So if <expr> is true (i.e. non-zero), then !(<expr>) is false (zero), and vice versa.