Function pointers and callbacks

Sdílet
Vložit
  • čas přidán 26. 09. 2013
  • See complete series on pointers here czcams.com/users/playlist?list=...
    In this lesson, we have explained use cases of function pointer through code examples. In previous video, we had explained basics of function pointers.
    See Bubble sort video here:
    • Bubble sort algorithm
    About event handling - You can think of a scenario where if something happens in a user interface, you want to perform some action. For example, upon a mouse click, you want to call some function. Many libraries give you a design where you can register a callback function to be called upon an event (like a mouse click). Library function will callback this function that you would register whenever the event occurs. Basically library function will call all functions registered for the event (stored in some list).
    See this Wikipedia article to know about events: en.wikipedia.org/wiki/Event_(c...)
    For practice problems and more, visit: www.mycodeschool.com
    Like us on Facebook: / mycodeschool
    Follow us on twitter: / mycodeschool

Komentáře • 179

  • @OzieCargile
    @OzieCargile Před 7 lety +95

    You are the best C language instructor I've found on CZcams. Clear and concise.

  • @yasserosama3405
    @yasserosama3405 Před 6 lety +42

    Using a function pointer instead of just calling a comparison function is more useful because then you can create many different comparison functions and still use that one sort function.
    This means you no longer have to have direct access to the implementation details of the sort function, thus helping to keep things cleaner and easier to see/manage. (this is not my comment , it's a reply to a question 3 years ago from now , I pasted it so new people coming could see it and maybe help them understand the real benefit/use of function pointers)

  • @Blaqueken
    @Blaqueken Před 7 lety

    The best online teacher on the Internet so far... as I'm concerned. Bravo! These concepts flew over my head back in class but now i understand. What a talent this guy. Very inspiring...

  • @cbeHotboyred1614
    @cbeHotboyred1614 Před 7 lety +43

    Man !!! You explain everything so great. I was so confused on this topic before your video. I had a similar program like this and need a way to change the comparison operator like < ,> !=, and == , but I didn't know how!! So i always just wrote duplicate code to change just one thing in it. Thanks, you explain everything perfectly!!!

  • @nawinksharma
    @nawinksharma Před 5 lety +2

    Thanks for separate series on pointer, this helped me in embedded system topic

  • @evertdekker3915
    @evertdekker3915 Před 9 lety +3

    Thanks, watched them all.
    Easy tot understand the basics of C with these video's.

  • @baconsledge
    @baconsledge Před 2 lety +1

    You explained everything about sorting but little about function pointers and callbacks. Like when a call back is really useful.

  • @NishantSingh-yt9em
    @NishantSingh-yt9em Před 4 lety

    Thank you for your efforts in explaining tricky things so easily.

  • @jianxiaohu8213
    @jianxiaohu8213 Před 4 lety +3

    This eps is another level!

  • @himanshusingh-sh7ih
    @himanshusingh-sh7ih Před 9 lety

    You made my concept very clear! Thanx a ton :)

  •  Před 6 lety +1

    It was really helpful. Thank you for the tutorial.

  • @rmarinero
    @rmarinero Před 5 lety

    I understood this within the first and a half minute, amazing and clear explanations!

  • @rd-tk6js
    @rd-tk6js Před 5 lety +1

    Thanks, excellent series on pointers !

  • @Heizler
    @Heizler Před 6 lety

    Very good explanation! Thanks!

  • @abhimanyumishra9455
    @abhimanyumishra9455 Před 9 lety +1

    Amazing Explanation!!

  • @MrJayesh05
    @MrJayesh05 Před 8 lety

    Brilliant job. Keep it up guys.

  • @saurabhsoni5047
    @saurabhsoni5047 Před 7 lety

    Good example used. Thumbs Up for that..
    Although, Regarding the compare function prototype for qsort in the last where you make the statement "const keyword is used here so that you cannot change the address stored in this pointer variable"
    It should be " cannot change the dereferenced value for that pointer variable "

  • @amalkms
    @amalkms Před 9 lety

    yours videos are really helpful , thank you very much ....

  • @darshilmodi6888
    @darshilmodi6888 Před 4 lety

    brillaint example and amazing explaination !! Keep going

  • @MustafaTaqi
    @MustafaTaqi Před 10 lety

    Thanks a lot, you are really doing a great job

  • @certified_car_simp1856

    wow this is so understandable if you're a beginner, great job

  • @syfaiz
    @syfaiz Před 5 lety

    Splendid explanation!

  • @venkyreddy5507
    @venkyreddy5507 Před 10 lety +1

    Awesome explanation bro.I really wondering that how could you do that.

  • @ibiixie
    @ibiixie Před 7 lety

    Had no idea this was possible, this sure will make my GUI system a lot easier to create! :>

  • @MartiinCarrillo
    @MartiinCarrillo Před 5 lety

    Great explanation!! Thanks a lot!

  • @XieQiu
    @XieQiu Před 8 lety +1

    thank you for posting this.

  • @Littleangel1306
    @Littleangel1306 Před 10 lety

    Thanks man your explanations are really good..........I appreciate you.

  • @flywittzbeats4008
    @flywittzbeats4008 Před 2 měsíci

    This is perfect haha, thank you. Makes so much more sense

  • @shubhamsuraj2725
    @shubhamsuraj2725 Před 4 lety +1

    dil jeet liya bhai ye video :)

  • @ericliudev
    @ericliudev Před 9 lety +2

    Hi, this is an amazing series of tutorials. The pointer to function is really interesting, however, language like Java doesn't have this mechanism. I guess we will have to use 2 classes to implement an interface and pass the interface as a argument to the method to achieve the same design.

  • @alisalamatian2418
    @alisalamatian2418 Před 3 lety +1

    Thanks for all of your videos. I really find them useful. I just still do not understand why we should use a function pointer when we can directly call the function. Could someone explain the difference to me?

  • @billigerfusel
    @billigerfusel Před 8 lety

    Wooot this is awesome explanation

  • @manjunath.r1513
    @manjunath.r1513 Před 10 lety

    it is really good sir thank you sir!!!!!!!!! keep going with your good job!!!!!!!!!!and help student like us.!!!

  • @ahbarahad3203
    @ahbarahad3203 Před 3 lety

    A very interesting use of function pointers that i have seen in real life projects is in Event Handling while passing delegates/function signatures to functions, under the hood its basically the same thing except the delegates also have an iterator.

    • @ahbarahad3203
      @ahbarahad3203 Před 3 lety +1

      Oh he mentions it at the end of the video, lol

  • @bibinio100
    @bibinio100 Před 10 lety

    Thanks a looooooooooooooooooooooooooooooooooooooooooooooooot of you are a wonderfull teacher !!!!!

  • @aadeshmehta
    @aadeshmehta Před 7 lety

    Hi, Thanks for the video. You explain really good.
    Which editor have you used?
    It seems really clean and helpful with function definitions and syntax.
    Are there any other such editors you recommend

  • @ediccartman7252
    @ediccartman7252 Před 7 lety +11

    Very good explanation, BUT.......For summary it would be useful to bring the code with both cases , like :
    void main()
    {
    int order, counter,
    a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
    printf( "Enter 1 to sort in ascending order,
    "
    Enter 2 to sort in descending order: " );
    scanf( "%d", &order );
    .................................
    if(order==1)
    Bubble(a,size,ascending);
    ..........................................................
    else
    Bubble(a,size,descending);
    And then it's clear, that in the1st case the function pointer will point to ascending , and in the 2nd - to descending.

  • @roshenw
    @roshenw Před 10 lety

    Thank youu soooooooo much really clear and helpful!!!!

  • @jamesward2946
    @jamesward2946 Před 7 lety

    This is great stuff!

  • @adithyashankar6562
    @adithyashankar6562 Před 6 lety

    Good explanation on callbacks

  • @emmanuelakpabio9529
    @emmanuelakpabio9529 Před rokem

    This is super duper amazing!😊

  • @anurag8725
    @anurag8725 Před 7 lety +1

    Why are we using a separate compare function when we already have compare (< or >) in our bubblesort function. How are we using this compare in bubblesort function along with"".
    Where is the user input flag you were talking about.

  • @moyam01
    @moyam01 Před 9 lety +6

    What is the difference between using the function pointer, and calling the compare function directly? for example, if within the sort function you just call compare(), and return the result. I've done something similar in Visual Studio, and it compiled and worked.

    • @lautarodelucia6480
      @lautarodelucia6480 Před 6 lety +3

      What comes to mind is that you cannot change the sorting order from main in that case. By using function pointers you could define two compare functions, one for increasing and other for decreasing order. They would only differ in the order of the returns ( swap 1 for -1). Then you can use command line arguments, for example, to choose your sorting order without touching the code.

    • @milanpatel3159
      @milanpatel3159 Před 5 lety

      the thing here is that if you don't have write permission to the BubbleSort() definition you can change sorting behavior from the main function. No need to touch BubbleSort()

  • @dawoodfarooq3605
    @dawoodfarooq3605 Před 7 lety +1

    Amazing. Keep up the good work (Y)

  • @ChienChiWang
    @ChienChiWang Před 9 lety

    Hi~~ I have a question.
    What are the variables the void pointer a and b in the function compare point to, after the program executes the function qsort ??
    Will they point to elements in array A??
    And the effect of return value of compare is to swap the two values in the elements?

  • @harshith_takkala
    @harshith_takkala Před 2 lety +1

    Awesome one

  • @saivenkat
    @saivenkat Před 2 lety +2

    Lets say you are designing a library function that would do something like sorting so anyone can just use your library function and sort. And you want to keep this sorting function generic, so data type can be anything. Then, how would you take the required information to sort from user of your library function? You cannot guess the comparison logic for a complex daya type. So, you would want to get the comparison logic too which can be passed as a function. So, in many cases when we are dealing with generic scenarios, function pointers make our life easier. It should be seen as a way to accept functionality as argument. So far, we knew that functions can accept only data, but now we know that even a function can be passed.

  • @ahmed_raaphat
    @ahmed_raaphat Před rokem

    BRILLIANT

  • @saeidsaati4021
    @saeidsaati4021 Před 4 lety +2

    Great tutorial with a good explanation thank you, I just think that in 14:34 const is using for preventing to change the "value" of the pointer not the address of it.

  • @cbeHotboyred1614
    @cbeHotboyred1614 Před 7 lety

    Do pointer function release its memory like the a regular function does when it finish executing OR do i have to delete it. If i have to delete it, How??
    Is it possible to delete the pointer function ...... like the way you delete the pointer variable in c++.

  • @mehulshah8470
    @mehulshah8470 Před 10 lety +1

    can u tell me the advantages of function pointer over calling function directly ?

  • @anghelutadragos1898
    @anghelutadragos1898 Před 8 lety +3

    Could you list some exercices for this playlist about pointers ?

  • @Jonathan-ru9zl
    @Jonathan-ru9zl Před 2 lety

    thank u . keep up the good work

  • @Praveenkumar4121994
    @Praveenkumar4121994 Před 7 lety

    tanx a lot!!! it was great help!!!!

  • @BYugandhar
    @BYugandhar Před 7 lety

    Thanks a lot sir for providing good explanation, but I don't get one thing while calling compare form main. From where it's taking

  • @SuperSayiyajin
    @SuperSayiyajin Před 5 lety

    Hi.Thanks for videos.I have a question. Is there any method or function to take array size? You typed Bubblesort( A,6 ); line. Can we use anything instead of 6?

  • @mahindersingh-wb3ik
    @mahindersingh-wb3ik Před 2 lety

    where are the arguments being passed from into the comparison function? I think form actual A[ ] right? If so, is it just comparing the first two numbers, 3 and 2, and proceed from there?

  • @nickeax
    @nickeax Před 3 lety

    Amazing, thank you very much.

  • @bradmorgan60
    @bradmorgan60 Před 3 měsíci

    Thank you so much.

  • @kanwarpandit8798
    @kanwarpandit8798 Před 4 lety

    Bhai. Kmaal Kar diya

  • @shivkrishna6157
    @shivkrishna6157 Před 8 lety +13

    10:13 why do you have to pass function pointer when you can use the "function compare" directly inside "the function BubbleSort"

    • @Phantom1037
      @Phantom1037 Před 7 lety

      Inside the main function when we called the bubble sort function, we gave as arguments : ( A, 6, compare).
      - A is an array and it returns the address of the first element, so the function declaration of bubbleSort should have the first argument as an pointer to iteger.
      - 6 is an integer so the second argument of the bubbleSort function should be an integer.
      - compare is a function and it returns the address of the compare function, so we need to pass a pointer to function as the third argument to the bubbleSort function.

    • @Arjunreddy-xi5ht
      @Arjunreddy-xi5ht Před 6 lety +6

      if there are more than 1 compare functions,instead of changing the code everytime you can just use a function pointer to call the required function and make the required comparison.

    • @KshitijKale
      @KshitijKale Před 4 lety +1

      My guess, it has something to do with the scope of the function. Since all the functions in the given example are global; they can be called effortlessly anywhere. But if some function was inside the main or any other function then it wouldn't be possible to directly call the function and hence a function pointer should be used.

    • @KshitijKale
      @KshitijKale Před 4 lety +1

      Ok, this one makes more sense. In the example of sorting integers using a pre-built quick sort algorithm we directly use the function. But since the definition of the actual function is not provided instead an extra parameter is allowed to be defined by the user himself so that they can still use the algorithm for quicksort and also make their own ranking function. In this way the source of code of qsort is safe and functionality is also maintained. If instead, we couldn't pass the function pointer then we would have to directly alter the qsort algorithm which in this case might even be possible but many times the source code isn't available. I hope this helps after this many years and please do share any insight that you might have discovered.

  • @souravsingh763
    @souravsingh763 Před 3 lety

    I was so confused with callback function working in JavaScript
    As i am familiar with c/c++ this callback in c and in JavaScript are same
    Thanks 👍

  • @ToanPhan03
    @ToanPhan03 Před 8 lety +1

    At 11:04 why we dont need to change *compare to *absolute_compare in void BubbleSort(.....) function. Also compare(A[j], A[j+1]) to absolute_compare(A[j], A[j+1]). But it still works fine because the value store in memory where pointer *compare point to?

    • @ankan2088
      @ankan2088 Před 7 lety

      nice observation. The bubble sort if you notice carefully takes the argument (A, 6, absolute_compare).
      So the int (*compare)(int, int) declared inside the void BubbleSort(int *A, int n, int (*compare)(int, int)) points to absolute_compare function instead of the compare function.
      Even if you changed the compare inside BubbleSort to another name( say, int (*ptr)(int, int)) it would work fine.
      I hope I explained it clearly. :)

    • @nakulnair497
      @nakulnair497 Před 7 lety

      I still didn't understand why *compare wasn't changed to *absolute_compare in bubblesort func definition

  • @ognjen297
    @ognjen297 Před 2 lety

    God bless you !

  • @pvsrinivas100
    @pvsrinivas100 Před 10 lety

    very informational thank you.

  • @nishanthkr2838
    @nishanthkr2838 Před 5 lety +1

    Thats some high level thinking there.

  • @Kapil_Thakar
    @Kapil_Thakar Před 10 lety

    great dear. useful.

  • @harikumar-cq1je
    @harikumar-cq1je Před 2 lety

    Even though the explanation is awesome. Still, I don't understand What's the difference between calling a function pointer and a normal function? I feel both do the same right? Even though you call Compare as a normal function that also does the same right? doe that makes any difference internally through memory?

  • @dickensowuor9091
    @dickensowuor9091 Před rokem

    Good job

  • @nikhilk7493
    @nikhilk7493 Před 4 lety +4

    9:29 you replace n-1 with i in inner loop

  • @amarnathnayak1145
    @amarnathnayak1145 Před 8 lety

    can someone explain me the last program, where he pass "tom" string to called function but dereferenced it by 'name' while printing. why didn't he write *name?

  • @chesteringosan6039
    @chesteringosan6039 Před 3 lety

    add: bubblesort(...){...for(...){int x =0;...for(...x += 1;){...}...if(x==0){break;}}}
    from a newbie with c, this additional statement will break when the array is already arranged, because the example from the video will loop as many as indicated in the arg, even if the array is already sorted

  • @dumamageswarisitaraman9501

    Is it possible to apply pointer arithmetic operation with function pointer.

  • @prankurhauhan
    @prankurhauhan Před 5 lety +1

    Hi, Thanks for the explanation it was great!!.
    just a remark/question: at 14:33 you said const void* a , we cannot modify the address that 'a' points to , which means you are implying 'a' is a constant pointer, but I think it is that the variable pointed by 'a' cannot be modified, means the *a = 3 is not allowed and a = &someOtherVariable is allowed.

    • @antilogism
      @antilogism Před 5 lety

      The "const" qualifier has the same effect on a pointer as it does on any other variable. Pointers, like a and b, are just variables containing an address and, with that qualifier, must always have the same value. However the data stored at those addresses are not bound by the qualifiers on those pointers. The data will follow the declarations that allocated the storage in qsort().

    • @AmitYadav-rp3ot
      @AmitYadav-rp3ot Před 4 lety

      @@antilogism
      Pointer to constant { const int *ptr }
      This indicates that the content at the address pointed by ptr cannot be changed, but changing the address pointed by ptr is allowed to change.
      Constant pointer to variable { int *const ptr }
      This indicates that the address pointed by ptr cannot be changed, however the content of the address is allowed to change.
      source: www.geeksforgeeks.org/const-qualifier-in-c/

  • @MiteshParekh
    @MiteshParekh Před 9 lety

    thank you !!!

  • @tarunkumar7563
    @tarunkumar7563 Před 7 lety

    code that you write to explain the concept ,is the syntax is same in both c and cpp

  • @stevefrt9495
    @stevefrt9495 Před 7 lety

    Thanks you so much

  • @utkarshjha657
    @utkarshjha657 Před rokem

    In the bubble sort if-expression, can we write :- if(compare(*(A+j), *(A+j+1) > 0) ?

  • @adityakrverma612
    @adityakrverma612 Před 10 lety +2

    Question to "mycodeschool" : this is really good video. Thanks for explaining. but question is how we are doing callback. It looks like regular calling of function when you call 'compare' inside bubblesort. Is that you mean is callback ? Can you please elaborate on callback. Also in the end of video you mentioned about callabck and event handling. That's what i am interested in. Is there any video or link on that ? Thanks !

    • @harikumar-cq1je
      @harikumar-cq1je Před 2 lety

      I had the same question too. What's the difference between calling a function pointer and a normal function? I feel both do the same right?

    • @sxve-x
      @sxve-x Před rokem

      8 years on and I have same question.

  • @luqmanahmad7929
    @luqmanahmad7929 Před 10 lety

    Great yaar

  • @jackofnotrades15
    @jackofnotrades15 Před 4 lety

    Hi, I need a bit of clarification about what you said at 14:38 about function parameter being const. You said it is passed as const because the address shouldnt be modified. But does it signify the address not being modified or value inside the address not be modified?
    Basically whats the difference between const void *p and void* const p?. Please reply

    • @Rohitsingh2410
      @Rohitsingh2410 Před 4 lety

      He is dead bro.
      yourstory.com/2014/06/techie-tuesdays-humblefool

    • @jackofnotrades15
      @jackofnotrades15 Před 4 lety +1

      @@Rohitsingh2410 I didnt knew that. May his soul rest in peace. And may be someone notice my comment and respond. May be he himself in someway.

    • @AmitYadav-rp3ot
      @AmitYadav-rp3ot Před 4 lety +1

      /////////////////////////////////////////////////////////////////////////////
      Pointer to constant { const int *ptr }
      This indicates that the content at the address pointed by ptr cannot be changed, but changing the address pointed by ptr is allowed to change.
      /////////////////////////////////////////////////////////////////////////////
      Constant pointer to variable { int *const ptr }
      This indicates that the address pointed by ptr cannot be changed, however the content of the address is allowed to change.
      source: www.geeksforgeeks.org/const-qualifier-in-c/

  • @ijazmuhammed7822
    @ijazmuhammed7822 Před 2 lety

    Than you so much

  • @dn9255
    @dn9255 Před 4 lety +1

    I don't get it. So why do we need to declare function pointers if we can just call the actual function like you did in the last example?

    • @VikasPoonia
      @VikasPoonia Před 4 lety

      In other programming languages we need this, like when an application waits for data and other things should be carried out. Like on CZcams, when you are watching a video, the next byte of the video should be downloaded. Suppose we have two function nested.. The first start the video and the nested one download the next byte of video to be seen. So the first executed itself but the second one is still waiting in memory for its required data. I hope you got it.
      We have in JavaScript:
      callback functions, async await and promises works on similar principles.
      function 1===> I am doing this.
      Function 2 ==> I am waiting for the next byte
      will return this as soon as I received it

  • @MrNams
    @MrNams Před 7 lety

    thanks

  • @aakash4351
    @aakash4351 Před 7 lety +1

    math.h not working for me, when i try to use abs. Instead of it i have to use stdlib.h.

  • @sureshdharavath1191
    @sureshdharavath1191 Před 10 lety +1

    with out using the callback can't we call the compare function from the if condition so that we no need to pass the address from the calling function. Is there any problem in this ?

    • @VV-cy9gf
      @VV-cy9gf Před 10 lety +5

      Using a function pointer instead of just calling a comparison function is more useful because then you can create many different comparison functions and still use that one sort function.
      This means you no longer have to have direct access to the implementation details of the sort function, thus helping to keep things cleaner and easier to see/manage.

    • @srujankumar1999
      @srujankumar1999 Před 8 lety

      +AMG POWER when we use function pointer...does it creates a slot for comparison function,above sort function on stack..for every comparision( comparing A[j],A[j+1] in a loop untill j

    • @yasserosama3405
      @yasserosama3405 Před 6 lety +1

      this explanation has solidified my understanding of function pointers and their use , thank you sir ! , please don't mind if I copy and paste your comment , as it would be new for people watching this video now , so they could easily see it and maybe help them understand like I did :)

    • @Arjunreddy-xi5ht
      @Arjunreddy-xi5ht Před 6 lety +2

      AMG POWER Nice explanation..it helped me understand the actual use of a function pointer,ThankYou.

  • @technicalskillslearning2052

    nice video

  • @msalem311
    @msalem311 Před 4 lety

    Why do you need the for loop with i?

  • @muthusamy450
    @muthusamy450 Před 10 lety

    were is the link for event handling?? can you please provide the same.. thanks!! the vedio was very good :) :)

  • @mcjgenius
    @mcjgenius Před rokem +1

    ty

  • @mahimajangra3248
    @mahimajangra3248 Před 4 lety

    why it is that we are putting the function pointer in the arguments, it can be called in function without declaring it in argument section also

  • @Linusovic
    @Linusovic Před 8 lety +1

    lifesaver

  • @abdelrhmanahmed1378
    @abdelrhmanahmed1378 Před 3 lety

    Are this is what happen we do run time Polymorphism is just function pointer using vtable and vrpointers !?

  • @avinashmv9686894578
    @avinashmv9686894578 Před 4 lety

    Awesome :)

  • @nikhilanand984
    @nikhilanand984 Před 3 lety

    for compare function pointer in BubbleSort why didn't we passed the address of the compare function instead we directly passed the arguments.

  • @suneelabbigari
    @suneelabbigari Před 4 lety

    Where do we need these call backs, in real time ?? Please help!!!

  • @rbsupercool
    @rbsupercool Před 10 lety

    i was waiting for this... thax...

  • @hirokaanf4287
    @hirokaanf4287 Před 10 lety

    why the first program (from the beginning until 2:39) is not working id u keep return 0; in the main function?

    • @mycodeschool
      @mycodeschool  Před 10 lety +1

      return 0 is main function is not forced by most compilers. Mine does not. So, often we do not write it.

  • @raghavjha9947
    @raghavjha9947 Před 3 lety

    I didn't understand how the ranking method changes help to the increasing and decreasing manner. Can anyone explain me.