Cannot declare variable of type off_t


(Richard Salvatore Hanulewicz) #1

We are attempting to declare a variable of type off_t to pass into our lseek function as described in the man pages, however we keep running into this error on compile:

error: a label can only be part of a statement and a declaration is not a statement

We have included types.h which gives us access to the typedef for off_t, and we really aren’t sure why it’s being treated this way, especially considering we were using ssize_t just fine and that was also defined in types.h.

Any ideas? We missing something? I mean, we are, definitely.


(Geoffrey Challen) #2

What line of code is generating this error?


(Benjamin Rueda) #3

Most likely the error is being caused by you trying to declare a variable within the case of a switch statement, which you cannot do.


(Geoffrey Challen) #4

When I Google the error message I got this, which discusses goto labels: http://stackoverflow.com/questions/18496282/why-do-i-get-a-label-can-only-be-part-of-a-statement-and-a-declaration-is-not-a. But I suspect that Ben is entirely correct, and that the error is inside sys_lseek.

There are some hacky workarounds mentioned in the SO post I linked to. But a cleaner fix is probably to hoist the variable declaration to the top of the function. I suspect that the compiler is probably smart enough to do the right thing anyway—i.e., defer allocating stack space for the variable until it is needed—and doing all of your variable declarations at the top of the function is much more readable. If you end up with too many, you probably need to refactor what is probably an overly complex function :slight_smile:.


(Richard Salvatore Hanulewicz) #5

Yep, you guys are absolutely correct. Didn’t realize you couldn’t declare variables in switch cases, but it makes sense. This should be enough information to fix the problem. Thanks!


(Blake Wallace Hurlburt) #7

You actually can declare a variable inside a case statement, just not on the first line.

The following is not allowed:
case FOO: off_t bar;

But the following will work:
case FOO: ; off_t bar;

As for why this isn’t allowed in C…this is why we have better languages now.


(Richard Salvatore Hanulewicz) #8

lmao what the hell

that’s kinda funny

also what are you doing this far back?


(Blake Wallace Hurlburt) #9

Just reading unread posts for fun haha