Home > Software design >  c:4:25: error: expected identifier or '(' before '{' token
c:4:25: error: expected identifier or '(' before '{' token

Time:05-02

I tried to implement template like functionality in C by use of macros, but for some reason it throws me the error "c:4:25: error: expected identifier or '(' before '{' token"

Here's the code

#include<stdio.h>
#include<stdlib.h>
#define test(name, type){\
    typedef struct{\
        type x;\
        type y;\
    }name;\
}
test(IntVec2, int);
int main(){
    printf("Hello, World!");
}

CodePudding user response:

Removing the brackets solves the problem as {typedef...} is not a valid declaration as stated by Mat in the comments.

CodePudding user response:

You need to remove those curly brackets { } covering your entire struct.

Final Code

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

#define test(name, type)            \
    typedef struct {                \
        type x;                     \
        type y;                     \
    } name;


test(IntVec2, int);

int main() 
{
    printf("Hello, World!"); 
}

CodePudding user response:

One way to debug this type of situation is to take a look at the output of the preprocessor. For exampl, we feed the following through the cpp preprocessor:

#define test(name, type){\
    typedef struct{\
        type x;\
        type y;\
    }name;\
}
test(IntVec2, int);

(I have omitted some of the code)

The result of the cpp program, is something like:

# 0 "test.c"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "test.c"

{ typedef struct{ int x; int y; }IntVec2;};

Now it becomes immediately apparent that the first { and last } should not have been in the macro definition.

Thus:

#define test(name, type)\
    typedef struct{\
        type x;\
        type y;\
    }name;
test(IntVec2, int);

Now leads to:

# 0 "test.c"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "test.c"

typedef struct{ int x; int y; }IntVec2;;

Note that even now, the ; at the end is obsolete (but relatively harmless in this specific case. Be very careful when using ; within macro definitions.

  • Related