Akuli / jou

Yet another programming language
MIT License
12 stars 4 forks source link

tutorial: Explain when to use pointer #496

Closed Akuli closed 7 months ago

Akuli commented 7 months ago

biberao is learning pointers, and asked a very good question that Jou's docs do not answer...

[00:21] biberao i still have issues with it
[00:21] biberao :D
[00:21] Akuli   what is your issue with it :)
[00:22] biberao usecases for pointers
[00:23] Akuli   maybe it helps that in python, every instance of a class is a pointer?
[00:23] Akuli   basically, you can refer to the same data in many places, instead of copying the data into many places
[00:23] biberao since python abstracts
[00:23] biberao i never pay attention
[00:23] Akuli    yes, but now you should, because you're learning c
[00:24] Akuli   also lists and dicts
[00:24] Akuli   look at this...
[00:24] biberao yes
[00:24] Akuli   !py add1 = (lambda x: x.append(1)); a=[]; add1(a); add1(a); a
[00:24] potti   Akuli: timed out
[00:24] Akuli   !py add1 = (lambda x: x.append(1)); a=[]; add1(a); add1(a); a
[00:24] potti   Akuli: timed out
[00:24] Akuli   hmm
[00:24] Akuli   !py print(1)
[00:24] potti   Akuli: timed out
[00:24] Akuli   :D
[00:25] Akuli   that's what you get when you develop the bot on a more powerful desktop and run it on ancient laptop :)
[00:25] biberao hahah
[00:25] biberao :D
[00:25] Akuli   anyway, a function call like "add1(some_list)" can append 1 to the end of a list
[00:25] Akuli   this wouldn't work, if the list was copied, but it is passed as a pointer
[00:26] Akuli   so the function can just look at the original list through a pointer instead of getting a copy of it
[00:26] biberao i see
[00:26] Akuli   very similar to set_to_500() function
[00:26] biberao when not to use a pointer?
[00:26] Akuli   when the value is small enough to be copied, or you just want to copy it
[00:27] Akuli   for example, if your function takes an integer and prints it, just pass it an integer
[00:27] biberao i see
[00:27] Akuli   you wouldn't do printf("%d\n", &my_num) for example
Akuli commented 7 months ago

More good questions...

[00:30] biberao so whats the difference between doing int * a vs int a then do &a
[00:30] biberao ?
[00:30] Akuli   "int a" and then "&a" means, you get a pointer to the variable
[00:30] Akuli   so when the function call is done, that pointer becomes invalid
[00:31] biberao i see
[00:31] Akuli   "int *a" means you don't make a pointer, you get a pointer from somewhere else and use it