Silverfin Silverfin - 3 months ago 12
C Question

unknown parse error when testing function

I have the function below which seems to act as it should, however when running the program through a testing program, I am given the errors: parse error: [int xSwapped = ((255 << nShift) | (255 << mShift));] and
undeclared variable `xSwapped': [return (~xSwapped & x) | nMask | mMask;]

int dl15(int x, int n, int m){
// calculates shifts, create mask to shift, combine result
// get number of bytes needed to shift, multiplying by 8
// get Masks by shifting 0xff and shift amount
// shift bits to required position
// combine results

int nShift = n<< 3;
int mShift = m<< 3;

int nMask = x & (255 << nShift);
int mMask = x & (255 << mShift);
nMask = 255 & (nMask >> nShift);
mMask = 255 & (mMask >> mShift);
nMask = nMask << mShift;
mMask = mMask << nShift;

int xSwapped = ((255 << nShift) | (255 << mShift));

return (~xSwapped & x) | nMask | mMask;

}


Not certain what im missing, thank you.

Answer

It looks like you are using a C compiler set to an old C standard. Prior to C99 you could not put executable statements before declarations.

You can fix this by moving the declaration of xSwapped to the top:

int nShift = n<< 3;
int mShift = m<< 3;

int nMask = x & (255 << nShift);
int mMask = x & (255 << mShift);
int xSwapped;                                   // Declaration
nMask = 255 & (nMask >> nShift);
mMask = 255 & (mMask >> mShift);
nMask = nMask << mShift;
mMask = mMask << nShift;

xSwapped = ((255 << nShift) | (255 << mShift)); // Assignment

return (~xSwapped & x) | nMask | mMask;