Unknown behaviour of assignment op in C [duplicate] - c

This question already has answers here:
Using assignment as a condition expression?
(5 answers)
Closed 4 years ago.
I don't know exactly cases of true and false returning from this construction. Can you describe it? Sry, if it is in a google search, I have not found.
( (struct->param = param_init()) == NULL )

param_init() this statement will be evaluated first and output will be stored in struct->param.
if struct->param contains NULL, if conditional will be evaluated to true
or if struct->param contains non NULL, if conditional will be evaluated to false.

if ( (struct1->param = param_init()) == NULL )
is an obfuscated way of writing
struct1->param = param_init();
if(struct1->param == NULL)
{
...
}
Use the latter form, assignment inside conditions should be avoided.

As assignment operator is having lowest priority that's why it always executes at last ,so in first Parentheses the function param_init() will get call first and the return value of this function will get assigned to structure pointer struct->param and at last value of struct->param will get compared with 0(NULL) and result(either 0 or 1) will return .
NOTE : Removal of Parentheses will change the result as it changes the precedence .

Related

question related to for loop condition statement in C [duplicate]

This question already has an answer here:
what is the difference between while(i>0) and while(i)
(1 answer)
Closed 6 months ago.
I am trying to run a program in C, where the following statement is used in the code.
What does the following statement mean in the for loop condition of the given code?
I understand i is being initialised with value 3; and i gets updated in i = i-1 ; but what does the condition part mean? why only i; should it not be i>0? Why both statements give the same output , i.e *** .
Code statements:
int main()
{
for(int i=3;i;i=i-1)
{
printf("*");
}
return 0;
}
Simply, i will be true when != 0. Since your program must keep going until i is zero, It will keep checking. Here's a list of what the condition returns:
i value
output returned by i
3
true
2
true
1
true
0
false (break)
C 2018 6.8.5.3 discusses the for statement, which has the form for (clause-1; expression-2; expression-3) statement, and paragraph 1 says:
… The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body…
6.8.5 4 says:
An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.
Therefore, with i for the controlling expression, the loop body is executed repeatedly until i compares equal to zero.

if we use if(a>b>c) # a being greater than all three results in false [duplicate]

This question already has answers here:
Math-like chaining of the comparison operator - as in, "if ( (5<j<=1) )" [duplicate]
(4 answers)
Closed 8 years ago.
i executed this following code in C;
#include<stdio.h>
#include<conio.h>
void main()
{
int a=15,b=10,c=5;
if(a>b>c)
printf("True");
else
printf("False");
getch();
}
output:
False
Please explain me why?
There is no ternary (or 'chained') > operator in C or C++. Thus your expression evaluates to ((a>b)>c) as evaluation is done left to right.
In C, true expressions evaluate to 1, and false ones to 0. In C++ my recollection is that they evaluate to boolean true or false, but then these type convert to 1 or 0 anyway, so the situation is much the same.
Using that principle, a>b will evaluate to 1 if a>b and to 0 otherwise. Therefore if a>b, the entire expression evaluates to 1>c, else to 0>c. As c is more than one, neither 1>c nor 0>c are true, and the output is always 0, or false, and the program will print False.
To achieve what I strongly suspect you really want, use ((a>b) && (b>c)).

If statement with ? and : [duplicate]

This question already has answers here:
What does the question mark and the colon (?: ternary operator) mean in objective-c?
(13 answers)
Closed 9 years ago.
I heard about a kind of If statement which use ? and : in C
I dont know how to use it and I cant find anything about it.
I need to use it in order to shorten my code
any help would be appreciated.
?: is ternary operator in C (also called conditional operator). You can shorten your code like
if(condition)
expr1;
else
expr2;
to
condition ? expr1 : expr2;
See how it works:
C11: 6.5.15 Conditional operator:
The first operand is evaluated; there is a sequence point between its evaluation and the
evaluation of the second or third operand (whichever is evaluated). The second operand
is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand
(whichever is evaluated),
As others have mentioned, it's called the ternary operator. However, if you didn't know that, it would be somewhat difficult to Google it directly since Google doesn't handle punctuation well. Fortunately, StackOverflow's own search handles punctuation in quotes for exactly this kind of scenario.
This search would yield the answer you were looking for. Alternately, you could search for "question mark and colon in c" on Google, spelling out the name of the punctuation.
First you have the condition before the ?
Then you have the expression for TRUE between ? and :
Then you have the expression for FALSE after :
Something like this:
(1 != 0) ? doThisIfTrue : doThisIfFalse
The ternary operator ?: is a minimize if statement which can reduce this:
if(foo)
exprIfTrue();
else
exprIfFalse();
To this:
(foo) ? exprIfTrue() : exprIfFalse() ;
Personally, I avoid using it because it easily becomes unreadable. The only good example of use is to display the status of a flag in a printf:
int my_flag = 1;
printf("My flag: %s\n", my_flag ? "TRUE" : "FALSE" );

What in the world does this statement mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this line of code mean?
I was reading an article on Opencv, and came across this:
for( i = 0; i < (faces ? faces->total : 0); i++ )
{
CvRect* r = (CvRect*)cvGetSeqElem(faces, i);
}
What in the world is this line supposed to mean:
i < (faces ? faces->total : 0)
It's the conditional operator.
The (faces ? faces->total : 0) tests faces. If it's true, then faces->total is returned and compared with i. Otherwise, if it evaluates to false, i is compared to 0.
EDIT: Per Femaref's comment, my code below (original response) is not equivalent. faces is likely modified by calling cvGetSeqElem, which in turn means that faces->total is probably modified as well. So, the condition may change in each iteration and, if faces is null (0), the loop exits.
Still, it's confusing (got me!). You could just as easily check for faces being null and exit the loop. The loop counter potentially changes in each iteration, is dependent upon the cvGetSeqElem function mutating it, and just bleh.
It is a shorthand if statement called the conditional operator. It is much the same as:
int count = 0;
if( faces )
count = faces->total;
for( i = 0; i < count; i++ ) {
CvRect* r = (CvRect*)cvGetSeqElem(faces, i);
}
So, if faces is null, count is 0 and the loop body never executes because the first test fails. Of course, you could just check first if that is null and avoid the whole thing together. That code is ugly IMO.
if( faces ) {
// do loop
}
Also, if faces->total is > 1 then you are just wasting cycles as only the last value returned by cvGetSeqElem will persist. Of course, that function could have other side effects that are being relied upon, which would make the code even more convoluted than it already is.
It's iterating up to a value that is a member in a structure.
If the structure pointer is NULL, then it iterates zero times.
It's a safety feature to prevent dereferencing a NULL pointer.
it is equivalent to
int output;
if(faces == 0)
output = 0;
else
output = faces->total;
(Note: this is just an explanation for the part in the for loop, not a replacement)
This is a trick in C. faces is in fact a pointer to a struct (visible by the -> dereferencing). There is no Boolean type in C, 0 means false, every other value is true. In this case, the pointer is implicitly cast to int and than interpreted as Boolean in the conditional operator.
The loop is terminated once the pointer to the struct is NULL. faces is changed in the cvGetSeqElem.
The ternary operator: "if faces is true, then faces->total, otherwise zero".

Recursion in C with Pre increment [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
int fact_rec(int n)
{
printf("%d\n",n);
if(n==1) return n;
else return fact_rec(--n)*n;
//else return n*fact_rec(--n); gives same result
//correct output comes for n*fact(n-1)
}
In the above recursive implementation of the factorial function,
fact_rec(5) returns 24. Whereas, if I use
n*fact_rec(n-1)
in place of
n*fact_rec(--n)
the output is correct : 120.
Also, it doesn't matter whether I use
n*fact_rec(--n)
or
fact_rec(--n)*n.
Shouldn't it matter if I use
n*fact_rec(--n)
or
fact_rec(--n)*n?
And shouldn't the output have
been 120 in all the cases?
return fact_rec(--n)*n
is dangerous. The order of argument evaluation is undefined in C (except for &&, ||, comma and ternary operators) so value for second occurrence of n could vary.
The rule of thumb: never use variable you are incrementing/decrementing twice in one expression.
Your confusion seems to be about the order - unlike the other answers, I am assuming you already know what --n does...
The compiler knows it needs the value of fact_rec(--n) before it can evaluate fact_rec(--n)*n whichever way round you write it, so the function is evaluated first, and the value of n multipled has always already been decremented.
There is actually no need to modify n at all. return n * fact_rec(n - 1) takes care of it and is the right way to do it.
--n in your function really means:
int fact_rec(int n) {
printf("%d\n",n);
if(n==1) {
return n;
} else {
n = n - 1; /* <---- effect of --n */
return fact_rec(n)*n;
}
}
The problem is here:
else return fact_rec(--n)*n;
you're decrementing n before the multipliation
so if n starts as 5 it runs as
return fact_rec(4)*4;
Edit: Down voted for a correct answer to the question? I don't get it.

Resources