I want to check an array in a condition. Let’s take this simple code below:
#include <stdio.h>
int main()
{
int array[] = {1,2,3,4,5}; // initializing an array
if(array[] == {1,2,3,4,5}) // using as condition
{
printf("worked");
}
else printf("not worked");
return 0;
}
But it gives an error:
In function 'main':|
C:\Python32\Untitled4.c|5|error: expected expression before ']' token|
||=== Build finished: 1 errors, 0 warnings ===|
So how should I use an array in a condition?
If you have a modern C compiler, at least C99, you can use a compound literal and a function to do that comparison:
memcmp(memory compare) compares the data to which the twopointers point.
(int[]){1,2,3,4,5}is the compound literal, something with the type in()and then an initializer in{ }as you have in the declaration of your variable.Edit: As Eric correctly remarks,
memcmpis only a valid comparison if the base type of your array (here this isint) has no padding bits or bytes. Forintthis is uncommon these days, so what I describe is fine on usual platforms. If you’d have other, more complex, data types some day, you would have to write your own comparison function for arrays of that type.