Advantages of using callback (in a non-event driven program)





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am looking into an callback example in:
https://en.wikipedia.org/wiki/Callback_(computer_programming)



#include <stdio.h>
#include <stdlib.h>

/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
int val1 = numberSource();
int val2 = numberSource();
printf("%d and %dn", val1, val2);
}

/* A possible callback */
int overNineThousand(void) {
return (rand()%1000) + 9001;
}

/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}

/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}


I understand all the functions. However, I am wondering except reducing a line, what's the advantage of doing:



PrintTwoNumbers(&overNineThousand);


rather than just using them like regular functions:



int a = overNineThousand();
PrintTwoNumbers(a);


Thanks!










share|improve this question





























    1















    I am looking into an callback example in:
    https://en.wikipedia.org/wiki/Callback_(computer_programming)



    #include <stdio.h>
    #include <stdlib.h>

    /* The calling function takes a single callback as a parameter. */
    void PrintTwoNumbers(int (*numberSource)(void)) {
    int val1 = numberSource();
    int val2 = numberSource();
    printf("%d and %dn", val1, val2);
    }

    /* A possible callback */
    int overNineThousand(void) {
    return (rand()%1000) + 9001;
    }

    /* Another possible callback. */
    int meaningOfLife(void) {
    return 42;
    }

    /* Here we call PrintTwoNumbers() with three different callbacks. */
    int main(void) {
    PrintTwoNumbers(&rand);
    PrintTwoNumbers(&overNineThousand);
    PrintTwoNumbers(&meaningOfLife);
    return 0;
    }


    I understand all the functions. However, I am wondering except reducing a line, what's the advantage of doing:



    PrintTwoNumbers(&overNineThousand);


    rather than just using them like regular functions:



    int a = overNineThousand();
    PrintTwoNumbers(a);


    Thanks!










    share|improve this question

























      1












      1








      1








      I am looking into an callback example in:
      https://en.wikipedia.org/wiki/Callback_(computer_programming)



      #include <stdio.h>
      #include <stdlib.h>

      /* The calling function takes a single callback as a parameter. */
      void PrintTwoNumbers(int (*numberSource)(void)) {
      int val1 = numberSource();
      int val2 = numberSource();
      printf("%d and %dn", val1, val2);
      }

      /* A possible callback */
      int overNineThousand(void) {
      return (rand()%1000) + 9001;
      }

      /* Another possible callback. */
      int meaningOfLife(void) {
      return 42;
      }

      /* Here we call PrintTwoNumbers() with three different callbacks. */
      int main(void) {
      PrintTwoNumbers(&rand);
      PrintTwoNumbers(&overNineThousand);
      PrintTwoNumbers(&meaningOfLife);
      return 0;
      }


      I understand all the functions. However, I am wondering except reducing a line, what's the advantage of doing:



      PrintTwoNumbers(&overNineThousand);


      rather than just using them like regular functions:



      int a = overNineThousand();
      PrintTwoNumbers(a);


      Thanks!










      share|improve this question














      I am looking into an callback example in:
      https://en.wikipedia.org/wiki/Callback_(computer_programming)



      #include <stdio.h>
      #include <stdlib.h>

      /* The calling function takes a single callback as a parameter. */
      void PrintTwoNumbers(int (*numberSource)(void)) {
      int val1 = numberSource();
      int val2 = numberSource();
      printf("%d and %dn", val1, val2);
      }

      /* A possible callback */
      int overNineThousand(void) {
      return (rand()%1000) + 9001;
      }

      /* Another possible callback. */
      int meaningOfLife(void) {
      return 42;
      }

      /* Here we call PrintTwoNumbers() with three different callbacks. */
      int main(void) {
      PrintTwoNumbers(&rand);
      PrintTwoNumbers(&overNineThousand);
      PrintTwoNumbers(&meaningOfLife);
      return 0;
      }


      I understand all the functions. However, I am wondering except reducing a line, what's the advantage of doing:



      PrintTwoNumbers(&overNineThousand);


      rather than just using them like regular functions:



      int a = overNineThousand();
      PrintTwoNumbers(a);


      Thanks!







      c callback






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 23:11









      EdamameEdamame

      5,0842487172




      5,0842487172
























          3 Answers
          3






          active

          oldest

          votes


















          2














          This is a trivial example of what's known as a Higher Order Function.



          In this particular example, it isn't very useful. You're right that it would be easier to just pass the data directly.



          It's a technique that allows for the generalization of functions though, and is very helpful in reducing code duplication when used properly.



          A typical example is the map function that transforms a list:



          var arr = [1, 2, 3];
          var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

          print(newArr); // Prints [2, 3, 4]


          Without higher order functions, you would have to write the same looping code that comprises map every time you want to transform a list. What if I wanted to add 2 to each element somewhere else? Or multiple each by 5? By passing a function, you can tell it how you want it to transform each item, without worrying about the iteration.



          As noted in the comments, another example would be sorting functions. They allow you to pass a function that determines sort order. Without that ability, you would need to write a new sorting function for each different sort order and element type.





          Sorry I couldn't answer this in C. I understand what's going on in the code you've posted, but I don't know C, so I couldn't give good example code that uses HOFs.






          share|improve this answer





















          • 1





            I'm curious: How often have you seen a C program use map()?

            – EOF
            Nov 22 '18 at 23:25






          • 1





            @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

            – Carcigenicate
            Nov 22 '18 at 23:28





















          0














          If the question is just computing one element, then yes, a callback is not very useful.



          Now if we consider that the function may need to call the callback several times in a (non-)deterministic way, then a callback is required.



          Typically, one of the most common callback in C is qsort where the callback is mandatory.






          share|improve this answer































            0














            There are at least two situations in which callbacks are useful:




            • Functions in which a task is performed repeatedly on some data. The example given in the comments is good: a comparison function passed into a sort function as a callback is a good example of a useful callback.

            • Enumeration functions. This is when you ask a library for a list of objects and you want to act on each one. You would pass a callback to the enumeration function. Example: EnumWindows.






            share|improve this answer
























            • Second situation is still looping on data, just that the data is not given as an argument.

              – Matthieu Brucher
              Nov 22 '18 at 23:51












            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438949%2fadvantages-of-using-callback-in-a-non-event-driven-program%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            This is a trivial example of what's known as a Higher Order Function.



            In this particular example, it isn't very useful. You're right that it would be easier to just pass the data directly.



            It's a technique that allows for the generalization of functions though, and is very helpful in reducing code duplication when used properly.



            A typical example is the map function that transforms a list:



            var arr = [1, 2, 3];
            var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

            print(newArr); // Prints [2, 3, 4]


            Without higher order functions, you would have to write the same looping code that comprises map every time you want to transform a list. What if I wanted to add 2 to each element somewhere else? Or multiple each by 5? By passing a function, you can tell it how you want it to transform each item, without worrying about the iteration.



            As noted in the comments, another example would be sorting functions. They allow you to pass a function that determines sort order. Without that ability, you would need to write a new sorting function for each different sort order and element type.





            Sorry I couldn't answer this in C. I understand what's going on in the code you've posted, but I don't know C, so I couldn't give good example code that uses HOFs.






            share|improve this answer





















            • 1





              I'm curious: How often have you seen a C program use map()?

              – EOF
              Nov 22 '18 at 23:25






            • 1





              @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

              – Carcigenicate
              Nov 22 '18 at 23:28


















            2














            This is a trivial example of what's known as a Higher Order Function.



            In this particular example, it isn't very useful. You're right that it would be easier to just pass the data directly.



            It's a technique that allows for the generalization of functions though, and is very helpful in reducing code duplication when used properly.



            A typical example is the map function that transforms a list:



            var arr = [1, 2, 3];
            var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

            print(newArr); // Prints [2, 3, 4]


            Without higher order functions, you would have to write the same looping code that comprises map every time you want to transform a list. What if I wanted to add 2 to each element somewhere else? Or multiple each by 5? By passing a function, you can tell it how you want it to transform each item, without worrying about the iteration.



            As noted in the comments, another example would be sorting functions. They allow you to pass a function that determines sort order. Without that ability, you would need to write a new sorting function for each different sort order and element type.





            Sorry I couldn't answer this in C. I understand what's going on in the code you've posted, but I don't know C, so I couldn't give good example code that uses HOFs.






            share|improve this answer





















            • 1





              I'm curious: How often have you seen a C program use map()?

              – EOF
              Nov 22 '18 at 23:25






            • 1





              @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

              – Carcigenicate
              Nov 22 '18 at 23:28
















            2












            2








            2







            This is a trivial example of what's known as a Higher Order Function.



            In this particular example, it isn't very useful. You're right that it would be easier to just pass the data directly.



            It's a technique that allows for the generalization of functions though, and is very helpful in reducing code duplication when used properly.



            A typical example is the map function that transforms a list:



            var arr = [1, 2, 3];
            var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

            print(newArr); // Prints [2, 3, 4]


            Without higher order functions, you would have to write the same looping code that comprises map every time you want to transform a list. What if I wanted to add 2 to each element somewhere else? Or multiple each by 5? By passing a function, you can tell it how you want it to transform each item, without worrying about the iteration.



            As noted in the comments, another example would be sorting functions. They allow you to pass a function that determines sort order. Without that ability, you would need to write a new sorting function for each different sort order and element type.





            Sorry I couldn't answer this in C. I understand what's going on in the code you've posted, but I don't know C, so I couldn't give good example code that uses HOFs.






            share|improve this answer















            This is a trivial example of what's known as a Higher Order Function.



            In this particular example, it isn't very useful. You're right that it would be easier to just pass the data directly.



            It's a technique that allows for the generalization of functions though, and is very helpful in reducing code duplication when used properly.



            A typical example is the map function that transforms a list:



            var arr = [1, 2, 3];
            var newArr = arr.map(x => x + 1); // Pass a function that adds one to each element

            print(newArr); // Prints [2, 3, 4]


            Without higher order functions, you would have to write the same looping code that comprises map every time you want to transform a list. What if I wanted to add 2 to each element somewhere else? Or multiple each by 5? By passing a function, you can tell it how you want it to transform each item, without worrying about the iteration.



            As noted in the comments, another example would be sorting functions. They allow you to pass a function that determines sort order. Without that ability, you would need to write a new sorting function for each different sort order and element type.





            Sorry I couldn't answer this in C. I understand what's going on in the code you've posted, but I don't know C, so I couldn't give good example code that uses HOFs.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 30 '18 at 4:45

























            answered Nov 22 '18 at 23:20









            CarcigenicateCarcigenicate

            18.6k53262




            18.6k53262








            • 1





              I'm curious: How often have you seen a C program use map()?

              – EOF
              Nov 22 '18 at 23:25






            • 1





              @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

              – Carcigenicate
              Nov 22 '18 at 23:28
















            • 1





              I'm curious: How often have you seen a C program use map()?

              – EOF
              Nov 22 '18 at 23:25






            • 1





              @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

              – Carcigenicate
              Nov 22 '18 at 23:28










            1




            1





            I'm curious: How often have you seen a C program use map()?

            – EOF
            Nov 22 '18 at 23:25





            I'm curious: How often have you seen a C program use map()?

            – EOF
            Nov 22 '18 at 23:25




            1




            1





            @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

            – Carcigenicate
            Nov 22 '18 at 23:28







            @EOF Likely never. When explaining why someone might use HOFs however, map is the probably the simplest, most straightforward example. I made a reference to sorting functions as well since that's likely more relevant to C.

            – Carcigenicate
            Nov 22 '18 at 23:28















            0














            If the question is just computing one element, then yes, a callback is not very useful.



            Now if we consider that the function may need to call the callback several times in a (non-)deterministic way, then a callback is required.



            Typically, one of the most common callback in C is qsort where the callback is mandatory.






            share|improve this answer




























              0














              If the question is just computing one element, then yes, a callback is not very useful.



              Now if we consider that the function may need to call the callback several times in a (non-)deterministic way, then a callback is required.



              Typically, one of the most common callback in C is qsort where the callback is mandatory.






              share|improve this answer


























                0












                0








                0







                If the question is just computing one element, then yes, a callback is not very useful.



                Now if we consider that the function may need to call the callback several times in a (non-)deterministic way, then a callback is required.



                Typically, one of the most common callback in C is qsort where the callback is mandatory.






                share|improve this answer













                If the question is just computing one element, then yes, a callback is not very useful.



                Now if we consider that the function may need to call the callback several times in a (non-)deterministic way, then a callback is required.



                Typically, one of the most common callback in C is qsort where the callback is mandatory.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 23:20









                Matthieu BrucherMatthieu Brucher

                17.7k52445




                17.7k52445























                    0














                    There are at least two situations in which callbacks are useful:




                    • Functions in which a task is performed repeatedly on some data. The example given in the comments is good: a comparison function passed into a sort function as a callback is a good example of a useful callback.

                    • Enumeration functions. This is when you ask a library for a list of objects and you want to act on each one. You would pass a callback to the enumeration function. Example: EnumWindows.






                    share|improve this answer
























                    • Second situation is still looping on data, just that the data is not given as an argument.

                      – Matthieu Brucher
                      Nov 22 '18 at 23:51
















                    0














                    There are at least two situations in which callbacks are useful:




                    • Functions in which a task is performed repeatedly on some data. The example given in the comments is good: a comparison function passed into a sort function as a callback is a good example of a useful callback.

                    • Enumeration functions. This is when you ask a library for a list of objects and you want to act on each one. You would pass a callback to the enumeration function. Example: EnumWindows.






                    share|improve this answer
























                    • Second situation is still looping on data, just that the data is not given as an argument.

                      – Matthieu Brucher
                      Nov 22 '18 at 23:51














                    0












                    0








                    0







                    There are at least two situations in which callbacks are useful:




                    • Functions in which a task is performed repeatedly on some data. The example given in the comments is good: a comparison function passed into a sort function as a callback is a good example of a useful callback.

                    • Enumeration functions. This is when you ask a library for a list of objects and you want to act on each one. You would pass a callback to the enumeration function. Example: EnumWindows.






                    share|improve this answer













                    There are at least two situations in which callbacks are useful:




                    • Functions in which a task is performed repeatedly on some data. The example given in the comments is good: a comparison function passed into a sort function as a callback is a good example of a useful callback.

                    • Enumeration functions. This is when you ask a library for a list of objects and you want to act on each one. You would pass a callback to the enumeration function. Example: EnumWindows.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 23:34









                    mnisticmnistic

                    7,24611025




                    7,24611025













                    • Second situation is still looping on data, just that the data is not given as an argument.

                      – Matthieu Brucher
                      Nov 22 '18 at 23:51



















                    • Second situation is still looping on data, just that the data is not given as an argument.

                      – Matthieu Brucher
                      Nov 22 '18 at 23:51

















                    Second situation is still looping on data, just that the data is not given as an argument.

                    – Matthieu Brucher
                    Nov 22 '18 at 23:51





                    Second situation is still looping on data, just that the data is not given as an argument.

                    – Matthieu Brucher
                    Nov 22 '18 at 23:51


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438949%2fadvantages-of-using-callback-in-a-non-event-driven-program%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                    ComboBox Display Member on multiple fields

                    Is it possible to collect Nectar points via Trainline?