Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"error: expected ';', ',' or ')' before numeric constant" is coming up to my code

The program is about function making an average. I get an error:

error: expected ';', ',' or ') before numeric constant

within the avg_array() function whenever I build it. Help would be appreciated, thanks!

#include <stdio.h>      
#define SIZE 5

// Prototypes
int avg_array (int*, int);          

main()
{
    int values[SIZE];
    int avg;
    int i;

    printf("Enter 5 numbers please. \n");

    for(i=0; i<SIZE; i++)
    {   
        scanf("%d", &values[i]);
    }

    avg = avg_array(values, SIZE);
    printf("\n The avg of the array is %d \n", avg);

    getchar();
    getchar();
} // end main()


/* Implement avg_array() WHERE THE ERROR PERTAINS */
avg_array(int my_array[], int SIZE)
{
    int sum;
    int i;
    int fxn_average;

    for(i=0; i<SIZE; i++)
    {
        sum = sum + my_array[i];
    }

    fxn_average = (sum/SIZE);

    return (fxn_average);
}
like image 848
madLad Avatar asked Feb 22 '16 01:02

madLad


1 Answers

You are using the identifier SIZE as an argument. This is also a macro that gets converted to 5 by the preprocessor. After the preprocessor applies the macros, it would look like

avg_array (int my_array[], int 5)

Since 5 is a numeric constant instead of an identifier, it generates an error. Change the variable name.

It looks like you also have a function signature missing a return type, which should match the prototype declared above. Try this instead:

int avg_array (int *my_array, int size)
{
    int sum = 0;
    int i;

    for(i=0; i<size; i++)
    {
       sum = sum + my_array[i];
    }
    return sum/size;
}

The variable sum should be initialized to 0. The local variable fxn_average is not needed because you can use just return sum/size; at the end instead.


I changed the type of the first argument from int[] (array of int) to int * (pointer to int) so the function definition matches the prototype given in the question. The function was declared as

int avg_array (int*, int);

These arguments have no identifiers; only their types are specified. This is valid C, but many style guides prescribe against it since naming arguments helps the reader understand meaning or intent. If you are writing a programming interface, for example, all the programmer will likely see is the function prototypes in a header file. It must be clear what the arguments are to write a correct function call. Anyway, adding in identifiers looks like:

int avg_array (int *my_array, int size);

which is the same as in the definition I used above.

like image 96
e0k Avatar answered Oct 19 '22 22:10

e0k