fvf fvf - 1 month ago 6
C Question

Appears to be valid C, but with error: "Expected identifier or '('"

So I am getting an error in the header file.
gcc is telling me that the error is at the 't' in the following line.

char* typeof(char*);


The corresponding code in the corresponding .c file is as follows.

char* typeof(char* word) {
int q = -1;
do {
char c = word[++q];
} while (c);
char* new = !q ? 0 : malloc(sizeof(char) * q);
while (q > 0) {
new[--q] = word[q] >= 'A' && word[q] <= 'Z' ? word[q] - 'A' : word[q] - 'a';
}
return new;
}


What other information do you guys need to know?

I am using a Mac, writing this code using vim within Terminal, and compiling using Mac's gcc.

fvfs-MacBook-Pro:src fvf$ which vi
/usr/bin/vi
fvfs-MacBook-Pro:src fvf$ ll /usr/bin/vi
lrwxr-xr-x 1 root wheel 3 Oct 5 11:33 /usr/bin/vi@ -> vim
fvfs-MacBook-Pro:src fvf$ ll /usr/bin/vim
-rwxr-xr-x 1 root wheel 1745984 Oct 19 05:38 /usr/bin/vim*
fvfs-MacBook-Pro:src fvf$ which gcc
/usr/bin/gcc
fvfs-MacBook-Pro:src fvf$ ll /usr/bin/gcc
-rwxr-xr-x 1 root wheel 18240 Oct 19 05:11 /usr/bin/gcc*


("ll" at the command line is an alias for "ls -l")

My IDE did not tell me it was a reserved word.

Answer

The proximate cause of the error (with the terrible error message) is you've used a reserved word (typeof) as your function name.

This error masks two more:

do {
  char c = word[++q];
} while (c);

c is not at scope for the while here.

char* new = !q ? 0 : malloc(sizeof(char) * q);

sizeof(char) is always 1 and thus superfluous, and you're not checking the return value of malloc for errors.