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!
  • Навчання та стиль

КОМЕНТАРІ • 132

  • @charlene2459
    @charlene2459 22 дні тому +2

    Loved this. I have been using structs as if they were classes, and function pointers as if they're class methods :'D

  • @RakeshSolanki1
    @RakeshSolanki1 Рік тому +5

    Everything about function pointers covered in one video. Great. Thanks.

  • @chbrules
    @chbrules 4 місяці тому +6

    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.

  • @naboulsikhalid7763
    @naboulsikhalid7763 Рік тому +11

    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

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +3

      You're very welcome, thank you for leaving such positive and encouraging feedback! :-)

  • @poopoo-dk4hu
    @poopoo-dk4hu День тому

    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

  • @lisandroiaffar4501
    @lisandroiaffar4501 2 місяці тому +1

    This one video condenses so much. Examples are excellent templates. Brilliant content, thank you so much

  • @aurinator
    @aurinator 4 місяці тому +3

    Another great & simple explanation, thanks for creating it!

  • @sakib1108051
    @sakib1108051 Рік тому +4

    The best function pointer video I have come across

  • @FrancoNSosa
    @FrancoNSosa Рік тому +3

    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.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      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. :-)

  • @Shivottmam
    @Shivottmam 2 місяці тому

    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 🇮🇳.

  • @silvioesilvanice
    @silvioesilvanice 8 місяців тому

    Thank you for this precious content. Im brazilian and I've following your videos

  • @oscarbarajas3610
    @oscarbarajas3610 3 місяці тому

    Quite beautiful functionality. Thanks for sharing.

  • @ValliNayagamChokkalingam
    @ValliNayagamChokkalingam Рік тому +2

    Thanks for this amazing video! Crystal clear explanation!

  • @enzocalzone5298
    @enzocalzone5298 5 місяців тому +6

    Callback functions in C make me appreciate virtual functions in C++ so much more :D

  • @moosyzeusy
    @moosyzeusy Рік тому +2

    Great explanation! I appreciate this very much!

  • @Danbotics
    @Danbotics 3 місяці тому +4

    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.

    • @vogesdg
      @vogesdg Місяць тому

      And also explain the syntax will greatly improve he video.

  • @bhagwatshinde648
    @bhagwatshinde648 2 роки тому +9

    Amazing video. Crystal clear explanation

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +3

      You're welcome!

    • @ramakrishna4092
      @ramakrishna4092 Рік тому +1

      @@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...

    • @festusnyabuto144
      @festusnyabuto144 Рік тому

      @@ramakrishna4092 that line declares a pointer, of a pointe to the function foo

  • @nobody_40432
    @nobody_40432 Рік тому +2

    thank you so much. You have become my go to channel to learn c.❤❤❤❤❤❤

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      You're very welcome Robel, I'm so glad to hear this has become your go to channel for learning C! ❤️

  • @anatoliishovah3108
    @anatoliishovah3108 Рік тому +2

    such an amazing explanation, thank you a lot!

  • @shroukalshoura5995
    @shroukalshoura5995 Рік тому

    Really you are great , i tried to understand it from several videos but yours was the best ❤

  • @jsmassinemassine1912
    @jsmassinemassine1912 Рік тому +3

    you did great job , thanks alot, from morocco

  • @Barzi2001
    @Barzi2001 4 місяці тому

    This channel is very good!

  • @umutabali
    @umutabali Місяць тому +1

    Brilliant content, thank you so much

  • @eyalshain5244
    @eyalshain5244 Місяць тому +1

    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!

  • @AhmadAsmndr
    @AhmadAsmndr 7 місяців тому

    Your videos are amazing, thank you very much

    • @PortfolioCourses
      @PortfolioCourses  7 місяців тому

      You’re very welcome, I’m glad you’re enjoying the videos! :-)

  • @try-restart
    @try-restart 6 місяців тому

    Great video. Thank-you.

  • @PHXKHEEDGAMING
    @PHXKHEEDGAMING Рік тому +2

    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

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      I'm glad to hear it helped you, and you're welcome! 🙂

    • @PHXKHEEDGAMING
      @PHXKHEEDGAMING Рік тому

      @@PortfolioCourses I know I’ve been bugging since I found your channel. I’m sorry 😞.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Haha that's OK

  • @duds_sn
    @duds_sn 3 місяці тому

    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

  • @ahmadibrahim3969
    @ahmadibrahim3969 8 місяців тому

    Great video thanks a lot❤

  • @MrTeen-ul7yc
    @MrTeen-ul7yc 6 місяців тому +1

    So is_freezing can be thought of as a higher order function right?

  • @yahirgonzalez6679
    @yahirgonzalez6679 4 місяці тому

    Thanks, man!

  • @muneerbasha1958
    @muneerbasha1958 Рік тому

    Best explanation sir

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Thank you very much Muneer, I'm glad you enjoyed the explanation! :-)

  • @arminiuscherusci4410
    @arminiuscherusci4410 Місяць тому

    Great video

  • @soumeshkundu8798
    @soumeshkundu8798 3 місяці тому

    After seeing this video , why i am being so confident to build a high level language using c 🙃

  • @ionguzun3952
    @ionguzun3952 2 роки тому +2

    Thanks bro🙂😊

  • @martinnyagah4313
    @martinnyagah4313 Рік тому

    Hey, thank you so much for this awesome course! So I was just wondering, can we relate function pointers to call-back functions?

  • @chaitanyadubakula
    @chaitanyadubakula 5 місяців тому

    At 12:37, is the freeze_check function call thing analogous to a, say, a lambda function in python or similar?

    • @bultvidxxxix9973
      @bultvidxxxix9973 4 місяці тому

      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);

  • @yclept9
    @yclept9 6 місяців тому

    How do you declare a function pointer x to a function that returns the function to call next? e.g.
    while(x=(*x)());

  • @cigmorfil4101
    @cigmorfil4101 2 місяці тому

    08:45 why the elses ? When the return occurs it cannot get to the next statement which is the if.

  • @pedronunes4072
    @pedronunes4072 Рік тому +1

    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?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +2

      Thanks Pedro! :-) I’m calling the function twice so I can test it twice with different user input values.

    • @pedronunes4072
      @pedronunes4072 Рік тому +1

      @@PortfolioCourses Ooooh lol thanks!!

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      You’re welcome! :-)

  • @festusnyabuto144
    @festusnyabuto144 Рік тому

    Hello, which code editor are you using in the video?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Hi Festus, in this video I am using Xcode on a Mac. :-)

  • @jonathanmoore5619
    @jonathanmoore5619 Рік тому

    Great video. Do function pointers dangle? Do we have to NULL them after use?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      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! :-)

    • @jonathanmoore5619
      @jonathanmoore5619 Рік тому

      @@PortfolioCourses thanks, that does help. Appreciated.

  • @sparkybrit
    @sparkybrit Рік тому

    Can select_operation have a parameter? If so, how would that be declared?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      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) ....

  • @mnr_02
    @mnr_02 7 місяців тому

    please say the name of the IDE or program you're using for coding and compiling, thanks in advance.

  • @qqmayakashi
    @qqmayakashi 4 місяці тому

    i learned pointers when I'm learning arduino and got fall in love with C so here am i learning pointers 😅

  • @fancywaifu9821
    @fancywaifu9821 Рік тому +2

    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?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +4

      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. :-)

    • @fancywaifu9821
      @fancywaifu9821 Рік тому

      @@PortfolioCourses Thank you!

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      @@fancywaifu9821 You're welcome! 🙂

    • @odissey2
      @odissey2 4 місяці тому

      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

  • @amabelarbi5538
    @amabelarbi5538 Рік тому

    in 3:47 why there's no need to deference the pointer , in that case are'nt we gonna have the adresse ???

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      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. :-)

  • @fifaham
    @fifaham Рік тому

    Nice

  • @salmantechnologies282
    @salmantechnologies282 Рік тому +1

    Can we use the Arrow operator with the function pointer
    as we using it in pointer to structure

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      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.

    • @salmantechnologies282
      @salmantechnologies282 Рік тому

      @@PortfolioCourses Thanks Sir I appreciate 👍

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      You're welcome! :-)

    • @seankayll9017
      @seankayll9017 4 місяці тому

      @@PortfolioCourses But can structs have members that are function pointers? Great videos btw. Very clear to understand.

  • @yigitcoban9823
    @yigitcoban9823 Рік тому

    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.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      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! :-)

    • @yigitcoban9823
      @yigitcoban9823 Рік тому

      @@PortfolioCourses wow thanks ✌️

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      @@yigitcoban9823 You're welcome! 🙂

    • @OrabyDance
      @OrabyDance Рік тому

      @@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

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      @@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.

  • @koleso1v
    @koleso1v 4 місяці тому +1

    I still do not understand why we can omit * when dereferencing function pointets.

    • @StackMemory0x00
      @StackMemory0x00 Місяць тому +1

      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.

  • @maorberenstein2540
    @maorberenstein2540 Рік тому

    Sanks men you pro

  • @muneerbasha1958
    @muneerbasha1958 Рік тому

    Please make function pointer within a structure as member with examples

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Hmm, maybe I can do a video on that topic one day, thank you for the idea. :-)

  • @bhagwatshinde648
    @bhagwatshinde648 2 роки тому +1

    Can you make video on structure pointer

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +1

      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

    • @bhagwatshinde648
      @bhagwatshinde648 2 роки тому

      @@PortfolioCourses ok

  • @syntactic_sugarboyy
    @syntactic_sugarboyy Рік тому

    🖤🖤

  • @franciscoarciganolasco6027
    @franciscoarciganolasco6027 2 місяці тому

    Esto es joya

  • @takisbakalis
    @takisbakalis 3 місяці тому

    i love you

  • @johnnygarcia7297
    @johnnygarcia7297 11 місяців тому +19

    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

    • @PortfolioCourses
      @PortfolioCourses  11 місяців тому +3

      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. :-)

    • @dominikbaricak9589
      @dominikbaricak9589 6 місяців тому +7

      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.

    • @johnnygarcia7297
      @johnnygarcia7297 6 місяців тому

      @@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

    • @Redditard
      @Redditard 4 місяці тому

      ​@@dominikbaricak9589that's not the point here, but by your logic chemists etc should learn physics too

  • @windowsbuilderthegreat3121
    @windowsbuilderthegreat3121 2 роки тому +2

    Does C have anonymous functions

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +1

      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. 🙂

  • @looploop6612
    @looploop6612 6 місяців тому

    hard to understand the syntax

  • @awekeningbro1207
    @awekeningbro1207 3 місяці тому

    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?

    • @PortfolioCourses
      @PortfolioCourses  3 місяці тому

      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.

  • @bultvidxxxix9973
    @bultvidxxxix9973 4 місяці тому

    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.

  • @stephanek9008
    @stephanek9008 Рік тому

    I am still confused 😭

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      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.

  • @overbored1337
    @overbored1337 2 місяці тому

    Its a shame that they decided to use this wierd syntax in c

    • @arminiuscherusci4410
      @arminiuscherusci4410 Місяць тому

      What do you mean? It’s great

    • @overbored1337
      @overbored1337 Місяць тому

      @@arminiuscherusci4410 short answer
      c: typedef int (*func(int, int);
      cpp: using func = std::function;

  • @fannypack7705
    @fannypack7705 Місяць тому

    can you do a pointers for c++

  • @soumeshkundu8798
    @soumeshkundu8798 3 місяці тому

    After seeing this video , why i am being so confident to build a high level language using c 🙃