0
Declaring and defining a function in C
The below is an example from the Functions in C lesson. My question is: Why is the int named 'y' in the definition, and not named 'result'? Also, would it be okay to name the int 'result' in the definition? I replaced it for 'y' in the definition and the output was the same. Thank you for considering my question, I appreciate all help :) #include <stdio.h> /* declaration */ int square (int num); int main() { int x, result; x = 5; result = square(x); printf("%d squared is %d\n", x, result); return 0; } /* definition */ int square (int num) { int y; y = num * num; return(y); }
5 Respuestas
+ 4
You can name your variables anything. Variable names can be reused in this scenario because there scope is limited to the block they are defined in.
+ 3
Yes you can name it result instead of y. However it is a good practice to name different variables with different names.
In main you have already a variable named result and the variable you are declaring in the function square is another variable. So you name it differently to avoid confusion.
If you want to make it clear that y is the result of the operation you could name it "rslt" or "squareResult" or anything you want.
Again you could give the same name to two different variables, but you should not.
edit: just to avoid confusion...
"Again you could give the same name to two different variables" that belongs to different scopes ",but you should not."
You can't have 2 variable with the same name within the same scope. It is quite intuitive, but worth to be said.
+ 2
Int y means y variable is declared as integer and results also integer
+ 2
Såñtösh
Avinesh
Davide
Thanks to everyone! I understand why those variables are not actually the same variable now, and that makes perfect sense why they should not be named the same. The variable result is the outcome of that specific function in the code, and y is the outcome of the function definition. It is the same reason why 'int x' is not declared as 'int num' in the main code. I figured it was something obvious but I just needed a different perspective, which you all provided so thank you!
0
Thank you Såñtösh. I appreciate your answer. However, that isn't quite what I meant. I know that they are both declared as integers, but aren't they the same variable in this case? Why are they named different things?