Declaring and defining a function in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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); }

10th Nov 2020, 5:06 AM
CODECAT
CODECAT - avatar
5 Answers
+ 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.
10th Nov 2020, 5:53 AM
Avinesh
Avinesh - avatar
+ 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.
10th Nov 2020, 11:29 AM
Davide
Davide - avatar
+ 2
Int y means y variable is declared as integer and results also integer
10th Nov 2020, 5:11 AM
Sâñtôsh
Sâñtôsh - avatar
+ 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!
10th Nov 2020, 9:08 PM
CODECAT
CODECAT - avatar
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?
10th Nov 2020, 5:20 AM
CODECAT
CODECAT - avatar