0

I have MPLab V8.43 installed and just installed the C18 complier for programming. Whenever I try and build a small test code it halts at the first variable declaration. It says there is a syntax.

unsigned char counter;

doesn't look wrong to me...even did it as unsigned char counter[1]; and it still tossed a syntax error back at me. What gives? Any ideas?

Chef Flambe
  • 885
  • 2
  • 15
  • 35
  • Never mind...turns out you can't declare from within the main function in embedded world. – Chef Flambe May 03 '12 at 04:08
  • Not true, you can declare from within the main function in C, including the embedded world. It just has to be at the top of a block. – Adam Casey May 03 '12 at 16:10

3 Answers3

1

Local variables must be declared at the top of a block (in this case, a function.) This is according to the C89 standard.

These are acceptable:

void functionname(void)
{
    unsigned char counter;

    /* rest of code */
}

void functionname(void)
{
    /* code */

    for (unsigned char counter = 0; counter<30; counter++)
    {
    }

}

This is not acceptable:

void functionname(void)
{
    /* code */

    unsigned char counter = 0; 

    /* more code */

}
Adam Casey
  • 949
  • 2
  • 8
  • 24
0

As You have counter variable with char datatype. But its not an array or string.

  so you can't access it by counter[1].
  • I don't see in his original question where he's trying to access it with counter[1]. Perhaps it was edited. – Adam Casey May 03 '12 at 16:11
0

You can define local variables in main, but they should be defined, such that they don't follow the variable assignment block or the code execution block.

This is a valid variable declaration/defintion in MPLAB C18:

void main ()
{
    /* Declare or Define all Local variables */
    unsigned char counter;   
    unsigned char count = 5;

    /* Assignment Block or the code Execution Block starts */ 
    conter++;
    count++; 
}

However, this isn't valid, and will cause a ‘Syntax Error’:

void main ()
{
    /* Declare or Define all Local variables */
    unsigned char count = 5;

    /* Assignment Block or the code Execution Block starts */ 
    count++; 

    /* What??? Another variable Declaration / Definition block */ 
    unsigned char counter;     /* Hmmm! Error: syntax error */ 
}

Hope that helps!

Cyclops
  • 108
  • 5