Function Pointers | C Programming Tutorial
Вставка
- Опубліковано 2 бер 2022
- How to use function pointers (i.e. pointers to functions) in C, including a demonstration of some use cases such as callback functions. Source code: github.com/portfoliocourses/c.... Check out www.portfoliocourses.com to build a portfolio that will impress employers!
- Навчання та стиль
Loved this. I have been using structs as if they were classes, and function pointers as if they're class methods :'D
Everything about function pointers covered in one video. Great. Thanks.
Beautiful! I can't believe how helpful these basics are. You have to have a strong foundation to build great things on. Thank you so much for these. Please continue to make more great content for the C language. When you run out of language basics, try code design (like handle-based design) or how to properly write out a multi-file program with all the typical things people do.
this is my second time to watch this lesson, and the picture is more cleared. all what is explained has a sens and targeted the main core of pointer and its their use. You put all such effort to make it accessible and detailed for US, a work that has a GREAT MERIT. thank you
You're very welcome, thank you for leaving such positive and encouraging feedback! :-)
I haven’t programmed in C in a two years and watched this out of curiosity but damn this video made it all click again
This one video condenses so much. Examples are excellent templates. Brilliant content, thank you so much
Another great & simple explanation, thanks for creating it!
The best function pointer video I have come across
Thank you for the positive feedback! :-)
Great video! A few days ago I was researching for ways to introduce some sort of polymorphism in my generic linked list library when I stumbled upon function pointers. It completely blew my mind. I had not even the slightest idea you could do this with functions! It's crazy!
Actually, I've been looking for this solution for quite a long time, but as I didn't know much of C or programming in general I didn't even know how to look for it. It wasn't until I started learning OOP fundamentals recently that I started getting hints of it. So, it's a particularly satisfying discoverment!
Today I could finally start trying this out in my programs, but I'm having trouble understanding some things. In college we've been taught that a good programming practice is to declare functions, then define / implement them. In a similar manner, we've also learned from Abstract Data Types (I dunno the acronym in english, in my country is TDA) to declare all the interface's functions in the .h file, then define them all in a .c file.
Without going much further, I was making a function "printData" that recieves a void pointer to some data and a pointer to a function to print that data according to its type (print_int if it's an integer, print_string and so on). I did an empty project and put everything only in the main.c file to be minimalistic. I first tried declaring all the functions above the main() function, then defining them below it, but it didn't work. Then I noticed that it does work when you just do it above the main function (declaration and implementation). My questions are:
- Why is this?
And, related to what I previously mentioned:
- How should I do it when working with multi-file projects?
It's also really plausible that I'm making a mistake so I'll double check, but ultimately my questions still stand.
I'm not sure why that wouldn't work to be honest, it should work. The only thing I can think of is that something was missing, like one of the function declarations or something like that. This video goes over how to create a library and split a program across multiple files: ua-cam.com/video/x8gsHFBW7zY/v-deo.html. After that video, this video about include guards may also be interesting: ua-cam.com/video/pF1_fXz5zN0/v-deo.html. :-)
This is the most beautifully and exceptionally well explained one of a kind video on a Function Pointers in C. Wow 🤩 amazing bravo 🙌 Thanks from India 🇮🇳.
Thank you for this precious content. Im brazilian and I've following your videos
Quite beautiful functionality. Thanks for sharing.
Thanks for this amazing video! Crystal clear explanation!
You're welcome Valli-Nayagam! :-)
Callback functions in C make me appreciate virtual functions in C++ so much more :D
Hahaha :-)
Great explanation! I appreciate this very much!
You're welcome! 🙂
I found this really interesting but I’m left with a basic question - why would you do this? Even undergrad level programming courses do something similar and launch into explaining a complicated topic without first setting up why you might need to do this thing. It might be how my older brain is wired but I really respond better to a teaching process like this:
* I want to do a thing (give a real world example of something that people will actually relate to)
* Explain (or better, show) why what you’ve learned so far won’t be able to do this thing
* Demonstrate how the new technique you’re about to teach solves this problem
* Get into the details and teach the new topic
I really do love the pacing and format of your videos (awesome work!) but I’m still struggling to connect it to a reason why this might be needed.
And also explain the syntax will greatly improve he video.
Amazing video. Crystal clear explanation
You're welcome!
@@PortfolioCourses hi sir I am revising every topic from your lectures I have a doubt here in function pointers , here is my question what is the meaning of this line ( void *(*foo)(int *) ) I am confused after seeing this my doubt is after void * is there right can you pls explain that line it will be helpful to meee.
Thank you so much sir love from India...
@@ramakrishna4092 that line declares a pointer, of a pointe to the function foo
thank you so much. You have become my go to channel to learn c.❤❤❤❤❤❤
You're very welcome Robel, I'm so glad to hear this has become your go to channel for learning C! ❤️
such an amazing explanation, thank you a lot!
You're very welcome Anatolii! :-)
Really you are great , i tried to understand it from several videos but yours was the best ❤
I'm glad the video helped you out Shrouk! :-)
you did great job , thanks alot, from morocco
You're welcome Jsmassine! 😀
This channel is very good!
Brilliant content, thank you so much
You're very welcome, I'm glad you liked it! :-D
Bro you videos are fireeee!
I think it will be good if you would do a vjdeo of you just building some sort of projects in c... for example implementing a vector in c, and you explain everything as you write it.
Anyways.... thank you!
Your videos are amazing, thank you very much
You’re very welcome, I’m glad you’re enjoying the videos! :-)
Great video. Thank-you.
Omg. You just saved my ass. 😂😂😂😂😂I’m so happy it’s funny. The very first example you made was more than enough for me to understand what I needed 😂😂😂I love you man. 😭😭😭
You didn’t add the second way of declaring the function pointer tho.
void (*function_pointer)(int) = &function;
Or maybe you did I haven’t finished watching haha.
But I’m definitely saved.
On to my next hurdle. Thanks a lot
I'm glad to hear it helped you, and you're welcome! 🙂
@@PortfolioCourses I know I’ve been bugging since I found your channel. I’m sorry 😞.
Haha that's OK
Holly! I've thought myself as a not so shitty programmer in C, having studied and developed somethings with effort but never heard anything near this concept. Amazing!
I can see using it together with 2D arrays to dynamic select the desired function, working with indexes rather than If or Switch.
Again, AMAZING
Great video thanks a lot❤
So is_freezing can be thought of as a higher order function right?
Thanks, man!
Best explanation sir
Thank you very much Muneer, I'm glad you enjoyed the explanation! :-)
Great video
I’m glad you liked it! :-)
After seeing this video , why i am being so confident to build a high level language using c 🙃
Thanks bro🙂😊
You’re welcome!
Hey, thank you so much for this awesome course! So I was just wondering, can we relate function pointers to call-back functions?
Never mind. just found my answer @12:30
Cool. :-)
At 12:37, is the freeze_check function call thing analogous to a, say, a lambda function in python or similar?
No, not at all. A lambda function would be a function that you define when you use it. For example in C++ you could call the freeze_check function like this:
is_freezing([](int temp){return (temp>273);});
In this case the function you pass to is_freezing is a lambda function.
However, C doesn't have lambda functions, so you have to do it in two lines:
bool freeze_K(int temp) {return (temp>273);}
is_freezing(freeze_K);
How do you declare a function pointer x to a function that returns the function to call next? e.g.
while(x=(*x)());
08:45 why the elses ? When the return occurs it cannot get to the next statement which is the if.
Great content! I have one question if you may answer pls
At 14:11 why are you calling the same function is_freezing with the same argument freeze_C, why are you repeating?
Thanks Pedro! :-) I’m calling the function twice so I can test it twice with different user input values.
@@PortfolioCourses Ooooh lol thanks!!
You’re welcome! :-)
Hello, which code editor are you using in the video?
Hi Festus, in this video I am using Xcode on a Mac. :-)
Great video. Do function pointers dangle? Do we have to NULL them after use?
Great question Jonathan. I would say "not really". The idea of a dangling pointer is when we have a pointer variable that points to memory that is no longer valid. So if the pointer variable was pointing to memory on the heap, then we free that memory, but don't set the pointer to NULL, then the pointer is a "dangling pointer". With pointers to functions, the functions are not dynamically allocated, they exist in the compiled code and we point to them with function pointers. So we can't really have the function pointer point to memory that is "no longer" valid. It's possible to have a pointer that's pointing to an incorrect memory address like any other pointer I suppose, but that's really a different issue than a dangling pointer where we have a pointer that was is still pointing to memory that was at one point valid but no longer is. Hopefully this helps! :-)
@@PortfolioCourses thanks, that does help. Appreciated.
Can select_operation have a parameter? If so, how would that be declared?
Yes, the parameter would go here:
int (*select_operation(double parameter))(int, int)
And we could provide an argument when we call select_operation...
... select_operation(2.5) ....
please say the name of the IDE or program you're using for coding and compiling, thanks in advance.
In this video I'm using Xcode a Mac. :-)
i learned pointers when I'm learning arduino and got fall in love with C so here am i learning pointers 😅
I've always wondered this but whats the point of calling functions like this instead of it doing without pointers? Is it faster or more memory safe?
Great question! :-) We can use function pointers to create "callback functions": en.wikipedia.org/wiki/Callback_(computer_programming). What this means is that we can pass a function X TO another function Y as an argument, and then function Y can call function X at some point to do some work "later". One advantage of this is that we can "customize" the work that function Y does by supplying some specific "functionality" via the function argument we provide. That link goes into more detail with some examples. :-)
@@PortfolioCourses Thank you!
@@fancywaifu9821 You're welcome! 🙂
Using a function pointer slows code, as an extra dereferencing step is needed. It is not good for time-critical code, as it adds some 10-20 clocks
in 3:47 why there's no need to deference the pointer , in that case are'nt we gonna have the adresse ???
Because it's a pointer to a function, and we're calling the function, we're not using a value like a pointer to a value like an int where we dereference the pointer to get the int value. In the case of pointers to functions we don't deference to call the function, and the 'reason' is just that it's different problems (accessing a value vs. calling a function) and ultimately it's because the creators of C made it that way. :-)
Nice
Thanks Firas! :-)
Can we use the Arrow operator with the function pointer
as we using it in pointer to structure
Great question! :-) No... we use the arrow operator with pointers to structs to access the members of the struct. We can use the arrow operator with unions too. But functions don't have members, so we don't use the arrow operator with pointers to functions.
@@PortfolioCourses Thanks Sir I appreciate 👍
You're welcome! :-)
@@PortfolioCourses But can structs have members that are function pointers? Great videos btw. Very clear to understand.
I dont know my english is enough for describing but ı am going to try. İn this topic ı have a question about something. When we have created normal function and then have created a pointer function, if we equalize this two of them. We dont use brackets in normal function but on the other hand we created pointer function not in main and later then in main function if we wanna use this pointer function with another pointer function, we use brackets in pointer function. For example minute 3.25 in the video is the example of first part and minute 9.39 is the example of second part. Or is there any problem that we use brackets in normal function while we are using pointer function.
So that second example at 9:39 is a function call to the function select_operation(). It's not assigning select_operation to the function pointer variable, it's assigning what select_operation() *returns* after it is called to the function pointer variable, and select_operation() is going to return a pointer to a function (subtract, multiply, etc.). Hopefully this helps! :-)
@@PortfolioCourses wow thanks ✌️
@@yigitcoban9823 You're welcome! 🙂
@@PortfolioCourses I am literally in love with your videos and solid content... just a small question for the select_operation function at 7:26 what is the difference between what you did and writing this function as follows : int* select_operation() which is a function returning a pointer to integer which should be (subtract, multiply, etc.) i tried this and it is still working fine with no errors just wondering what is the difference?
Thanks
@@OrabyDance int* select_operation() returns a pointer to an int, the function in the video returns a function which accepts two int parameters and returns an int. I believe you're not getting an error because in both cases, the function returns a pointer, and the rules around implicit pointer type conversion can allow for that, see this: stackoverflow.com/questions/52407576/can-you-assign-pointers-of-different-types-to-each-others.
I still do not understand why we can omit * when dereferencing function pointets.
This is a great question and here is the answer:
if you assign a function pointer using the syntax with & operator, you have to use the * dereference operator. Here is an example :
function_pointers = &function
in this case, you have to call the function by dereferencing it :
(*function_pointers)(9)
But if you assign a function pointers **without** &operator, you don't have to use the * dereference operator.
function_pointers = function
in this case, you can call it without * operator
(function_pointers)(9)
Pointers are tricky and take time to learn and master. Here is a playlist of Dr. Kevin's videos about pointers which I built over time:
ua-cam.com/video/2GDiXG5RfNE/v-deo.html
Watch these 9 videos many times until you feel comfortable with working with pointers
Dr. Kevin's channel is the best place to learn C for beginners. I have been following his channel and learning from him since he had just a couple of thousand subscribers and I'm so happy to see the channel has almost 150k now.
Best of luck.
Sanks men you pro
You're welcome Maor! :-)
Please make function pointer within a structure as member with examples
Hmm, maybe I can do a video on that topic one day, thank you for the idea. :-)
Can you make video on structure pointer
That's a good idea maybe one day I'll make a video specifically on that. It is covered a little bit in some videos you might like already: ua-cam.com/video/w5XM1N7hLgc/v-deo.html
@@PortfolioCourses ok
🖤🖤
Thank you Ekwueme! 🖤🖤
Esto es joya
i love you
haha thanks! :-)
I love your videos so much, this generation of programmers are really dumb and i feel like going back to the c/c++ programming days are what we truthly need for our understanding
I’m glad you love the videos Johnny, and I think there is big value in going back to the basics with languages like C. :-)
Study electrical engineering then. At deep level programming is just playing with electricity, logic gates and huge amount of physics and math. But understand all of this is not possible in one human life.
@@dominikbaricak9589 i've done that, i build a drone with arduino and then upgrade it with some machine learning models so i had to switch the arduino into a rasparry pi and it made me fall in love even more im currently a fullstack dev but im planning on switching into AI real soon
@@dominikbaricak9589that's not the point here, but by your logic chemists etc should learn physics too
Does C have anonymous functions
Anonymous functions are not officially part of the C standard, but gcc and clang both support features similar to anonymous functions: en.wikipedia.org/wiki/Anonymous_function#C_(non-standard_extension). Maybe one day I can cover these features. 🙂
hard to understand the syntax
I agree it’s tricky looking. :-)
it does not work. gave me compilation error:
int add(int x, int y) {
return x + y;
}
int sub(int x, int y) {
return x - y;
}
int mult(int x, int y) {
return x * y;
}
int div(int x, int y) {
return x / y;
}
int *(select_operation())(int, int) {
printf("select:
");
printf("1. Add\t");
printf("2. Subtract
");
printf("3. Multiply\t");
printf("4. Divide
");
int n;
scanf("%d
",&n);
if(n == 1) return add;
else if(n == 2) return sub;
else if(n == 3) return mult;
else if(n == 4) return div;
else return add;
}
int main() {
int (*operation)(int, int) = select_operation();
printf("enter two numbers:
");
int x, y;
scanf("%d
%d
",&x,&y);
operation(x,y);
return 0;
}
got this error: warning: returning 'int (*)(int, int)' from a function with return type 'int' makes integer from pointer without a cast [-Wint-conversion]
what's wrong?
The code in the video is found here: github.com/portfoliocourses/c-example-code/blob/main/function_pointers.c. I notice the * is outside the brackets where you have select_operation() defined.
8:22 that part was ugly. First you don't need an else when the if part returns. The code behind the if will only be executed if and only if the condition for the if statement was evaluated to false. It's not just unnecessary characters to type, it also breaks the alignment of the statements.
Secondly it should be a switch case anyways.
I am still confused 😭
Honestly function pointers are a pretty tough topic. Even if we understand the idea conceptually, the syntax is also tough to wrap our heads around. I think it's really important to have a good understanding of pointers before learning about function pointers, maybe this video can help a bit? :-) ua-cam.com/video/2GDiXG5RfNE/v-deo.html.
Its a shame that they decided to use this wierd syntax in c
What do you mean? It’s great
@@arminiuscherusci4410 short answer
c: typedef int (*func(int, int);
cpp: using func = std::function;
can you do a pointers for c++
After seeing this video , why i am being so confident to build a high level language using c 🙃