Anthony J
Anthony J

Reputation: 61

Getting an error "error: expected expression before..." when I try to call a function with parameters in C

My code looks like:

FILE *test
char line[50];
fp = fopen(arg[5], "r");

doSomething(File test, char line[50]);  // declare function
doSomething(fp, line[50]); // call function

I am getting an "expected error expression before 'FILE' error. I've tried many different variations of the syntax, but I still get this error, or more errors. I realize when I call the function, I just need to have the arguments within the same scope and to declare the function beforehand, which I thought I did.

I just want to be able to call the function without error.

Upvotes: 1

Views: 12925

Answers (4)

Sourav Ghosh
Sourav Ghosh

Reputation: 134366

The problem in your code is, without a forward declaration, the first assummed declaration is actually being interpreted as a function call [implicit declaration of a function]. There, the File test is being interpreted as actual argument, not a parameter. There, FILE being a reserved keyword and File test being no valid argument, the error is thrown.

In your code for the function declaration, move th3 declaration outside main(), please specify the return type for the function and correct the type of first parameter.

Change

 doSomething(File test, char line[50]);

to

 int doSomething(File * test, char line[50]);

Note: Always enable [and pay attention to] compiler warnings. With warnings enabled, your compiler should show you the warning

warning: implicit declaration of function

in these cases.

Also, the call is wrong. line[50] will reference the character just after your array. Change the call to:

doSomething(fp, line); // call function

Upvotes: 1

Michael Woyo
Michael Woyo

Reputation: 148

When you open a file in C, a pointer to the beginning of the file is returned. This is what you should pass around and not the actual file. The right was is as Gopi suggested.

Upvotes: 0

Shreesh
Shreesh

Reputation: 1

The declaration of function should be like this.

     doSomething(File *, char); 

Upvotes: 0

Gopi
Gopi

Reputation: 19874

doSomething(File test, char line[50]);

should be

doSomething(File *test, char line[50]);

I see that the function fopen() returns FILE * and you are trying to pass the return value to your function doSomething() so the first argument should be of type FILE * and not FILE

void doSomething( FILE *f,char a[])
{
  // Do your stuff
}

int main()
{
  char b[100] = "";
  FILE *fp = fopen("file","mode");
  doSomething(fp,b);
}

Upvotes: 0

Related Questions