CppMonster
CppMonster

Reputation: 1276

error C2059: syntax error : 'type'

I've got error:

main.c(10) : error C2059: syntax error : 'type'. 

What's wrong with this code?

#include <stdio.h>
#include <stdlib.h>

void getline(FILE* file, char* line)
{
    int c;
    size_t n = 0;
    while(c=fgetc(file)!='\n')
    {
      line[n++] = char(c);
    }
    line[n] = '\0';
}

int main(int argc, char* argv[])
{
    FILE* f;
    char* line = (char*)malloc(100);
    f = fopen("Saxo","r");
    if(f==NULL)
      return -1;
    getline(f,line);
    free(line);
    fclose(f);
    return 0;
}

Upvotes: 2

Views: 14450

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158469

Considering your name this probably is a confusion since C++ allows what are called explicit type conversions which are an expression:

line[n++] = char(c);

so this would compile fine in C++ but this does not exist in C so what you need to use is a plain cast:

line[n++] = (char)c;

but is not necessary in this case.

I would advise cranking up the warnings that would have indicated that this line is a problem:

 while(c=fgetc(file)!='\n')

clang warns us by default while gcc does not:

 warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
while(c=fgetc(file)!='\n')
      ~^~~~~~~~~~~~~~~~~~

note: place parentheses around the assignment to silence this warning
while(c=fgetc(file)!='\n')
       ^
      (                  )

Upvotes: 1

M.M
M.M

Reputation: 141554

line[n++] = char(c); is a syntax error. I guess you meant to cast:

line[n++] = (char)c;

NB. This cast actually has no effect, as int can be implicitly converted to char, which happens anyway because line[n++] has type char.

It would also be wise to check against EOF as well as \n in your loop, in case the file does not end with a newline.

Also: = has lower priority , so the line while(c=fgetc(file)!='\n') is going to set c to either 1 or 0. Some parentheses required to fix.

Upvotes: 3

user3400330
user3400330

Reputation:

You might be using a version of C that doesn't allow variables to be declared in the middle of a block. C used to require that variables be declared at the top of a block, after the opening { and before executable statements.

Already have a discussion from here

error C2275 : illegal use of this type as an expression

and here

http://social.msdn.microsoft.com/Forums/vstudio/en-US/693b03be-4198-4abc-8717-92c91f868437/error-c2059-syntax-error-type?forum=vclanguage

Upvotes: 0

Related Questions