← Previous | 🏠 Homepage | Next Chapter → |
Scope Rules: Who Knows What?
main() {
int i = 20;
display(i);
}
display(int j) {
int k = 35;
printf("%d", j);
printf("%d", k);
}
-
i
is known only insidemain()
. It’s local. -
k
is known only insidedisplay()
. Also local.
If display()
wants i
, main must share it (pass it like a gift ).
If main()
wants k
, display()
must return it (send it back ).
Moral of the story: What happens in a function, stays in that function.
Calling Convention: Left or Right?
fun(a, b, c, d);
C says, “Let’s start from the right!”
Yep, C passes arguments right to left.
Example:
int a = 1;
printf("%d %d %d", a, ++a, a++);
Looks like it should print 1 2 3
, right?
Nope! It prints 3 3 1
Why? Because of:
-
a++
passes1
(then a = 2) -
++a
makes it3
and passes3
-
Last
a
is now 3
Confusing? Yep
Just don’t do crazy stuff in printf()
— it's not a magic show
Library Functions & Prototypes
clrscr();
gotoxy(10, 20);
ch = getch();
These come from secret header files like conio.h
.
Each .h
file = a box of tools (aka prototypes).
-
stdio.h
→ for input/output tools -
math.h
→ for math nerd stuff -
conio.h
→ for console tricks
Want to look smart? Peek inside .h
files!
You’ll see stuff like:
void clrscr();
int getch();
If you don’t match the right tools with the right format, C will still compile but it might print garbage values
Advanced Function Features
Time to level up! Here come the cool moves:
1. Function Prototypes
C Thinks Every Function Returns int
So if your function gives a float
, you must tell C!
Bad:
square(float x) { return x * x; }
C says: “Hmm... must be int!” → Gives wrong result like 2 instead of 2.25
Good:
float square(float x) { return x * x; }
Also tell C before calling it:
float square(float);
Now C knows it's dealing with floats — no more math mistakes!
2. Returning Nothing? Use void
Want a function that just talks and doesn’t return anything?
void gospel() {
printf("Viruses are electronic bandits...\n");
printf("They eat nuggets of information...\n");
printf("And bite your bytes!\n");
}
void
means: "Don't expect anything back."
L;DR (Too Long; Didn’t Read)
- Variables live only inside the function where they’re declared.
-
C passes arguments from right to left.
-
Use
.h
files for library functions. -
Want to return a float? Declare it properly!
-
No return value? Use
void
.
No comments:
Post a Comment