You cannot use global variables as parameters of a function. That would make no sense either.
int multiplication (int a, int b)
What happens here in truth is that a
and b
are two separate function-local variables inside of the function multiplication
.
They are not references for the global variables with the same names.
As function-local variables have higher priority, they shadow the global variables at the scope of the function, which means that if you use/address a
or b
inside of the function, they refer to the local variables, not the global ones.
That's what the diagnostic of:
"declaration shadows a variable in the global scope"
says to you. The declaration of the local variables shadows the global variable declarations inside of the function multiplication
.
What you can do is pass the global variables as arguments by value to the function multiplication
:
#include <stdio.h>
int multiplication (int a, int b);
int a = 5, b = 10, c = 15, d = 20;
int main (void)
{
printf("Product: %d", multiplication(a,b)); // arguments, global variables.
}
int multiplication (int a, int b) // parameters, local variables.
{
return a * b;
}
Output:
Product: 50
In this way shadowing still occurs but it isn't problematic, if you add the specific -Wno-shadow
flag to turn off warnings/errors for shadowing. This is usually only a warning to hint you that shadowing occurs. Shadowing itself is not harmful.
That it is treated as error is caused by the -Werror
flag, which displays warnings as erros. -Werror
is great, but you should be able to differentiate real errors (issues that won't get the code compiled anyway) and only warnings which are just shown as errors to prevent code being executed with any reasonable things which potentially can give you issues with regard to the successful implementation of the algorithm or the execution.
Or just rename the parameters to a different name to make the compiler not show these warnings.
If you only want to use global variables inside of the function multiplication
, you could just use c = a * b;
inside of main()
and omit the whole function multiplication
then:
#include <stdio.h>
int a = 5, b = 10, c = 15, d = 20;
int main (void)
{
c = a * b;
printf("Product: %d", c);
}
Output:
Product: 50
To use a function which changes only global variables is considered as bad practice.
Side notes:
You should avoid global variables whenever possible, where you could pass values either by value or by reference as arguments instead.
If you got a lot of functions, where you need to pass the value of the same variable into it would make sense to use global variables.
Also as you seem to confuse the terms "argument" and "parameter", take a look at here:
What's the difference between an argument and a parameter?