My code compiles and runs but I still get a lint error message:
--- Module: LunchMenu_main.c (C)
} lunch[LUNCHES] =
LunchMenu_main.c: warning 956: (Note -- Non const, non volatile static or external variable 'lunch')
Although the use of non-constant static and external variables is demonstrated, using them has many pitfalls and they should be avoided unless there is no other reasonable solution. Is there any way I could avoid these kinds of variables or do I need these variables to fix this error? Here is my code:
struct Food
{
char *name;
int weight, calories;
} lunch[LUNCHES] =
{{(char *)"apple", 4, 100}, {(char *)"salad", 2, 80}};
int main(void)
{
int counter;
struct Food *foodPtr = &lunch[0];
printf("%-10s %-10s %-10s\n", "name", "weight", "calories");
for (counter = 0; counter < 2; counter++)
{
foodPtr = &lunch[counter];
printf("%-10s %-10d %-10d\n",
foodPtr->name, foodPtr->weight, foodPtr->calories);
}
return 0;
}
The warning is probably given since your variable
lunch
is defined using a type defined in the same C file, so you cannot define other variables in other compilation units using the same type, so giving your variable global visibility does not make sense. It should bestatic
.I beg to differ. Yes, they have some pitfalls, but I do not see any reason to avoid them at all cost. Used in a responsible way, they can help structure your code better.