I want to know if:
val1 = val2 = val3 ... = val6
I try this:
if (val1 == val2 == val3 == val4 == val5 == val6)
{
}
but it don't work, why?
I want to know if:
val1 = val2 = val3 ... = val6
I try this:
if (val1 == val2 == val3 == val4 == val5 == val6)
{
}
but it don't work, why?
The ==
operator only works between pairs of values. When you do this:
val1 == val2 == val3
What's really happening is this:
(val1 == val2) == val3
So if val1
and val2
are equal, the expression in the parenthesis evaluates to true:
true == val3
And then it checks whether true
== val3
, not whether val1
or val2
== val3
. You have to do this instead:
val1 == val2 && val1 == val3
This is getting pretty unwieldy for six variables though. Do you really have six local variables that you have to compare? Perhaps you should store them in an array of some sort. Then you can do:
bool all_equal(int *vals, int length) {
if (length == 0) {
return true;
}
int first = vals[0];
for (int i=1; i < length; i++) {
if (vals[i] != first) {
return false;
}
}
return true;
}
So instead of:
int val1 = ..., val2 = ..., val3 = ..., val4 = ..., val5 = ..., val6 = ...;
if (val1 == val2 && val2 == val3 && val3 == val4 && val4 == val5 && val5 == val6) {
...
}
You would to:
int vals[6] = {..., ..., ..., ..., ..., ...};
if (all_equal(vals, 6)) {
...
}
You can't chain the ==
operator. Do this:
if (val1 == val2 && val2 == val3 && val3 == val4 && val4 == val5 && val5 == val6) {
// they are all equal
}
Error Issue is already ably explained by other users, I just wanted to share an another approach.
I written a C code using variable number of arguments: 9.9. Variable numbers of arguments I hope you find it interesting
#include<stdio.h>
#include<stdarg.h>
typedef enum {FALSE, TRUE} boolean;
boolean isAllEqual(int count, ...){
va_list ap; // vlist variable
int num = 0;
boolean flag = TRUE;
//Step2: To initialize `ap` using right-most argument that is `c`
va_start(ap, count);
//Step3: Now access vlist `ap` elements using va_arg()
num = va_arg(ap, int);
while(--count){
if (num != va_arg(ap, int)){
flag = FALSE;
break;
}
}
//Step4: Now work done, we should reset pointer to NULL
va_end(ap);
return flag? TRUE: FALSE;
}
int main(){
if(isAllEqual(5, 2, 2, 2, 2, 2))
printf(" Yes, All are equal\n");
else
printf(" No, All are NOT equal\n");
if(isAllEqual(4, 2, 4, 2, 5))
printf(" Yes, All are equal\n");
else
printf(" No, All are NOT equal\n");
return 0;
}
Output:
Yes, All are equal
No, All are NOT equal
Check codepade.
My boolean isAllEqual(int count, ...)
function can check any number of integers, count = number of values you wants to compare. e.g. In isAllEqual(4, 2, 4, 2, 5)
first 4
means you wants to compare next four values.
A short theory in four points will help you to understand my code.
I would suggest writing a macro or a function(if it is array with big size or if it is allocated at runtime) in this case.