I just start to study functions in C and this stopped me. I want to write a function that searches for an element in a vector of SIZE elements. Here's the code:
#include <stdio.h>
#define SIZE 10
int find(int vet[], int SIZE, int elem);
int main()
{
int vett[SIZE] = {1, 59, 16, 0, 7, 32, 78, 90, 83, 14};
int elem;
printf ("Imput the element to find: ");
scanf ("%d", &elem);
find(vett[SIZE], SIZE, elem);
if (find == 1)
printf ("\nI find the element!");
else if (find == 2)
printf ("\nI did not find the element!");
return 0;
}
int find(int vett[], int SIZE, int elem)
{
int i;
int flag = 0;
for (i = 0; i < SIZE; i++)
if (vett[i] == elem)
flag = 1;
if (flag == 1)
return 1;
else
return 2;
}
Why does Code::Blocks say to me:
|4|error: expected ';', ',' or ')' before numeric constant|
||In function 'main':| |8|error: expected ']' before ';' token|
|14|error: 'vett' undeclared (first use in this function)|
|14|error: (Each undeclared identifier is reported only once|
|14|error: for each function it appears in.)|
|14|error: expected ']' before ';' token|
|14|error: expected ')' before ';' token|
|16|warning: comparison between pointer and integer|
|18|warning: comparison between pointer and integer|
|24|error: expected ';', ',' or ')' before numeric constant|
||=== Build finished: 8 errors, 2 warnings ===|
What did I do wrong?
You are using the preprocessor in places where you shouldn't; let me explain.
Your line
#define SIZE 10
tells the compiler that ALL occurences of the 4 letters "SIZE" are to be replaced by "10".
Which in your code will look like this:
int find(int vet[], int SIZE, int elem); // before preprocessor
int find(int vet[], int 10, int elem); // after preprocessor -> syntax error
The second line is not valid in C.
What you should do is try to not use your preprocessor definitions as variable names. For instance, what I do is: I name my preprocessor macros with CAPS (which you did) and always name my function variables with only CamelCase or smallletters.
edit: my suggestion:
int find(int vett[], int size, int elem);
int find(int vett[], int size, int elem)
{
int i;
int flag = 0;
for (i = 0; i < size; i++)
if (vett[i] == elem)
flag = 1;
if (flag == 1)
return 1;
else
return 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With