Compile time error as 'lvalue required' but not sure why [duplicate] - c

This question already has answers here:
Error: lvalue required in this simple C code? (Ternary with assignment?)
(4 answers)
lvalue required as left operand of assignment in conditional operator [duplicate]
(3 answers)
"error: lvalue required as left operand of assignment" in conditional operator
(1 answer)
C ternary expression-statement not working [duplicate]
(2 answers)
Getting error "lvalue required as left operand of assignment"
(6 answers)
Closed 3 years ago.
This code throws an lvalue required compile time error.
#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k < m ? k++ : m = k;
printf("%d", k);
}

Ternary operator has higher precedence than assignment, that's why your code is equal to (k < m ? k++ : m) = k;. Your compiler says that the value in brackets is not assignable.
What you want to do is:
#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k < m ? k++ : (m = k);
printf("%d", k);
}

The problem is here:
k < m ? k++ : m = k;
with the construct you want to assign a value, but you don't. I guess you want something like this:
k = (k < m) ? k+1 : m;
Now you will assign k a value depending on the condition k < m
if (k < m) -> k = k+1
otherwise -> k = m

Related

A weird syntax in C/C++ [duplicate]

This question already has answers here:
What does the integer suffix J mean?
(2 answers)
What does c++ constant value 1j mean? [duplicate]
(1 answer)
Why can't we do three-way comparison in C++? [duplicate]
(6 answers)
Comparing a variable to a range of values
(7 answers)
Closed 4 months ago.
Translation:
"After running the code below, what is the value of k?'
This question was from my friend's homework(we were senior highs). He didn't know how to deal with this, so he asked me and then I tried to test this on my computer(Debian 10, gcc-10.2.1). The result is (A) , which means the value of k is 6. I reflected on the if statement but still had no idea. It utterly made no sense - especially the syntax(who will even write code in that way?) . That's why I would like to ask this question. Perhaps that's a bug I haven't met before.
The C code:
#include <stdio.h>
int main() {
int i, j, k = 0;
for ( i = 0 ; i <= 2 ; ++i ) {
for ( j = 0 ; j <= 2 ; ++j ) {
if ( i != 1i != 2 && j != 1 ) {
k = k + j;
}
}
}
printf("%d\n", k);
return 0;
}
Why can the following if statement work?
if ( i != 1i != 2 && j != 1 )
And what's the value of 1i?

Found 2 liner C solution with ',' operator in for loop, can someone explain given comma operator statement?

Explanation:
I've following problem statement at hand, I came across an interesting 2 liner, C solution for it under leedcode discussion section. I tried to decompose it to understand what it means, and except one small line, I understood the rest. My question is at the end.
Leetcode Problem Statement:
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1: Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are
[1,5,6,8,9,10,12,13,...]. The 5th missing >>positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...].
The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
Two liner C solution:
int findKthPositive(int* arr, int arrSize, int k){
for (int arrCurrIndex = 0, counter = 1 ; (k && (arrCurrIndex < arrSize) ? ((arr[arrCurrIndex] != counter) ? k-- : ++arrCurrIndex) : k--) || (k = counter-1, 0) ; counter++);
return k;
}
For reference: Following is a similar algorithm that's being deployed, but its just cleaner to understand.
int findKthPositive(int* arr, int arrSize, int k){
for (int counter=1, arrCurrIndex=0; counter<10000; counter++) {
// exceed arr limits
if (arrCurrIndex < arrSize) {
if (counter == arr[arrCurrIndex]) { // found element in array
index++;
continue;
}
}
// missing element
k--;
if (k==0) {
return counter;
}
}
return 0;
}
My question:
What does following line in solution #1 means exactly?
(k = counter-1, 0)
======UPDATE ON ANSWER=======
I modified solution #1 in question slightly to make it more readable. It highlights what is going on with the given statement in question.
Here is the modified solution:
int findKthPositive(int* arr, int arrSize, int k){
// move counter out of the foor loop
int counter=1;
for (int arrCurrIndex = 0;
(k && (arrCurrIndex < arrSize) ?
((arr[arrCurrIndex] != counter) ? k-- : ++arrCurrIndex)
: k--); counter++);
return counter-1;
}
The binary comma operator , evaluates the first operand, discards the result and then evaluates the second one.
In the expression you posted we have
... || (k = counter-1, 0) ;
so counter-1 is actually assigned to k but its evaluation (k itself) is discarded so that 0 is used. Why 0? Because it is the neutral operand for logic or operator ||. In fact
X || 0 ==> X
In other words we have the expression
stuff_at_the_left || (k = counter-1, 0 )
that is evaluated as
stuff_at_the_left || 0
And since 0 is the neutral operand in logical or, the final evaluation is stuff_at_the_left.
The purpose of this weird expression is to cheat: the author at some point needed to assign that value to k but without adding more lines "ruining" the one liner. So they included the assignment in the logical expression making it neutral with comma operator combined with or operator's neutral operand.We also have to say that the assignment k=counter-1, 0 is performed only if all stuff_at_the_left is evaluated as 0 (due to the short circuiting nature of logical operators in C). The resulting expanded code is
if (!stuff_at_the_left)
k= counter-1;
Note: the comma operator has the lowest precedence among all the operators in C, and that's why the assignment is performed at first.

Warning comparison integer and pointer [duplicate]

This question already has answers here:
Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?
(5 answers)
Closed 6 years ago.
int b[5] = {1,2,3,4,5};
int *s = &b[0];
int *p = &b[1];
int *q = &b[2];
int *r = &b[2];
My question is when I compare p < q < r using if( p < q < r), I got the warning message.
What I thought is, first of all, (p < q) == True, so it's impossible to compare boolean with integer( address value of r). However, when True is considered as integer, it's 1. Right? So, 1 < r might make sense, in my guess.
What's wrong with my thought?
1 < r doesn't work because 1 is an integer and r is a pointer. Thus the warning.
My guess is you (a) meant to dereference the pointers, and (b) need to replace the chained comparisons with &&.
if (*p < *q && *q < *r)
You seem to be under the impression that the expression p < q < r translations to "p is less than q, q is less than r", which would be typical of a mathematical notation.
However, the C programming language doesn't necessarily follow mathematical conventions. What p < q < r actually translations to is p < q, which might be 0 or 1 depending upon whether that's false or true, followed by either 0 < r or 1 < r based on that previous difference.
As another user has pointed out, the proper way to write "p is less than q and q is less than r" is p < q && q < r.
Change your condition from:
if(p < q < r) {}
To:
if(p < q && q < r) {}

Assigning an int using the ternary conditional operator and the values of two other ints

In the Big Nerd Ranch C book, which I'm using to learn C, it is said that "whenever you have a scenario where a value is assigned to a variable based on a conditional, you have a candidate for the 'conditional/ternary operator', which is ?."
So my questions is, can someone explain to me the following code snippet:
int i = 20;
int j = 25;
int k = (i > j) ? 10 : 5;
if (5 < j - k) {
//First expression
printf("the first expression is true.");
} else if ( j > i ) {
//Second Expression
printf("The second expression is true.");
} else {
printf("Neither expression is true.");
}
The int k = (i > j) ? 10 : 5; in your example is equivalent to:
if (i > j)
{
int k = 10;
}
else
{
int k = 5;
}
The ternary operator is just a shortcut for special cases of if-conditionals when assigning a value based on a condition.
The rest of the snippet is not that hard to understand, if remove the incomplete else if snippet:
if (5 < j(25) - k(5)) == if (5 < 20)
{
printf("the expression is true.");
}
else
{
printf("the expression is false.");
}
Because 5 is smaller than 25 - 5 = 20, This program will print "the first expression is true".

What will the following code evaluate?

I had the following code in a test.I am confused about what (i,j) evaluates,while reading about the "," operator i found that it just evaluates the variables or functions but what does it do here?
main()
{
int i = 10, j = 20;
j = i ? (i, j) ? i : j : j;
printf("%d %d", i, j);
}
(i,j) is exactly the same as just j, because i is just a variable and evaluating it doesn't cause any side effect.
So basically it's just obfuscation here.
in (i,j), the , operator does nothing because the left-hand side expression does not have side-effects.
The assignment is thus equivalent to:
j = i? (j? i : j) : j;
And since i and j are non-zero, to j = i;
The comma operator can be used to link the related expressions together. A comma-linked list of expressions is evaluated left-to-right and the value of the rightmost expression is the value of the combined expression. It acts as a sequence point.
A sequence point guarantees that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.
So, any expression/assignment will be completed & only then will the next expression to the right be evaluated.
For example,
b=(a=4,a=5);
gives,
a=5
b=5
Also, note that the comma operator ranks last in the precedence list of operators in C.
It will print:
10 10
This is because you can break the expression down like:
j = i ? ((i, j) ? i : j) : j;
The comma operator evaluates to the last expression - so (i, j) == j. That is non-zero, so the center expression evaluates to i. 'i' being non-zero, the outer expression evaluates to i, so j is assigned to the value of i.
This is equivalent to:
int main() {
int i = 10, j = 20;
if (i != 0) {
(void)i; // Do nothing with i.
if (j != 0) {
j = i;
} else {
j = j; // Assign j to itself.
}
} else {
j = j; // Assign j to itself.
}
printf("%d %d", j);
}
Looks like typical software written test question. It is used to confuse candidates. As suggested by sepp2k above it is same as j. One more interview question
i = 10; j = 20;
1) k = i,j;
2) k = (i,j);
Answer for 1 will be 10 and answer for 2 will be 20. As coma operator doesnt do anything. I hope this will clear more.
It's not really doing anyting. It's evaluating the expression i, discards the result, evaluates the expression j and returns the result.
As evaluating the expression i has no side effects, (i,j) has the same meaning as just j.
main()
{
int i = 10, j = 20; // i=10, j=20
j = i ? /*if i */ ( (i, j) ? /* if j (1) */ i : /* else */ j ) : /* else */ j; // Added parenthesis and see (2)
printf("%d %d", i, j); // Will therefore print 10 10
}
it is equivallent to if(j) because (i,j) evaluate to j because i has no side effect.
all ifs evaluate to true because i and j are ints and are non zero

Resources