Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange parse error with C and dlc compiler

I have the following code:

int bitSwitcher = (1 << n) + ~0;
bitSwitcher = bitSwitcher << (32 + (~n + 1));
int arthShift = x >> n;
int logShift = arthShift ^ bitSwitcher;

int xSign = x >> 31;
int wasNegShift = xSign & logShift;
int wasPosShift = arthShift;

return wasNegShift ^ wasPosShift;

The line with the parse error is: int arthShift = x >> n;

The compiler also says, in the last line: return wasNegShift ^ wasPosShift; wasNegShift and wasPosShift are undeclared, which I assume because their declarations either directly use arthShift or use other variables whose declarations depend on arthShift.

I'm using something called the DLC compiler as part of a programming puzzle assignment. It's designed to make sure you follow the special rules (ex: you may only use certain values and operators). Occasionally I will get these weird "parse errors" (that is the only information it gives; "parse error" along with the number line. I don't suspect the error is related to the special rules, because when you do violate them, it's pretty explicit about it.

1. I've tried re-typing the code. I have copied and pasted from an online C editor/compiler (which does not catch this error) and, just in case some weird characters might have crept in, I re-typed the entire function. I've had random characters creep in before, like copy-pasted quotation marks that couldn't be read by Django, while using the same text editor as I'm using now (Sublime). Checking for this possibility didn't help though.

2. Not only does the online compiler I use not raise any parse errors, neither does the GCC.

3. I'm doing the same exercise as this person: Parse Error in C He/she also got the same error, and no one seemed able to figure it out.

If there is a magical soul out there who may have any ideas or possible solutions... :) Perhaps someone with mastery of compiler knowledge may know obscure cases where problems like this can arise. I'm at the mercy of this compiler at the moment.

PS: If you happen to figure out the purpose of this function, I'm already aware there is at least one case where it does not work. Haha I just want to figure this error out.

like image 495
Spag Guy Avatar asked Feb 13 '23 10:02

Spag Guy


1 Answers

The compiler you are using probably only supports C89. In C89, variables must be declared in the beginning of a block, which is not true anymore in C99.

Try moving the declarations to the beginning like this:

int foo()
{
    int arthShift, logShift, xSign, wasNegShift, wasPosShift;  //declarations
    int bitSwitcher = (1 << n) + ~0;
    bitSwitcher = bitSwitcher << (32 + (~n + 1));
    arthShift = x >> n;
    logShift = arthShift ^ bitSwitcher;

    xSign = x >> 31;
    wasNegShift = xSign & logShift;
    wasPosShift = arthShift;

    return wasNegShift ^ wasPosShift;
}
like image 174
Yu Hao Avatar answered Feb 15 '23 10:02

Yu Hao