Functions in C

Discussion in 'Mac Programming' started by Quboid, Dec 3, 2006.

  1. Quboid macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #1
    Hey guys, i'm first year computer systems engineering student. I am about ot finish the semester and finals got me by the throat. The thing is i missed my final programming class, in which the professor taught "functions in c", he thought how to declare, implement and call functions. I am really lost on that topic and thats exactly what the final exam would entail. Anyone have any advice?
     
  2. bronxbomber92 macrumors regular

    Joined:
    Nov 23, 2006
    #2
    Here's and example of a function that will add two numbers together...

    Code:
    //declaration
    float add( float num1, float num2 );
    
    float add( float num1, float num2 ) {
        float sum;
        sum = num1 + num2;
    
        return sum;
    }
    
    int main() {
        float numbers[3] = { 1, 2, 0 }
    
        numbers[2] = add( numbers[0], numbers[1] );
    
        //should print "3"
        cout << numbers[3] << endl;
    
        return 0;
    }
    Feel free to say if you need more elaboration ;)
     
  3. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #3
    trying to make sense out of it, but i think it would be easier with more comments. Thanks!!!
     
  4. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #4
    Here is the same thing in strict C, instead of C++:

    Code:
    #include <stdio.h>
    
    /* function prototype */
    float add( float, float);
    
    float add( float num1, float num2 ) {
        float sum;
        sum = num1 + num2;
    
        return sum;
    }
    
    int main() {
    
    /* declare and fill array */
    float numbers[3] = { 1, 2, 0 };
    
      /* call function with elements 0 and 1 (the first and second) and */
      /* return the result to the third element of the array */
        numbers[2] = add(numbers[0], numbers[1]);
    
        /* should print "3" */
        printf("%f\n", numbers[2]);
    
        return 0;
    }
    
     
  5. bronxbomber92 macrumors regular

    Joined:
    Nov 23, 2006
    #6
    Ohh, sorry. I didn't realize it was C, not C++
     
  6. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #7
    float add( float num1, float num2 )

    is this declaring variables num1 and num2 as floats?

    float sum

    is this declaring variable (local) sum as a float?

    numbers[2] = add(numbers[0], numbers[1])

    i'm guessing that "add" is the name of the function and the contents of the array in position 0 and 1 will be assigned to the variables num1 and num2.

    Am i right? or dead wrong.
     
  7. mduser63 macrumors 68040

    mduser63

    Joined:
    Nov 9, 2004
    Location:
    Salt Lake City, UT
    #8
    Yes, but it's more than that. It is saying that add() takes two arguments, num1 and num2, both of which are floats. num1 and num2 don't have to be declared again in the body of the add() function, but they do have to appear in both the function prototype and the line at the top of the function definitition (those two lines should be identical).
    Yes, exactly.
    You're right. "add" is the name of the function that was declared/defined above and the things in parentheses are the arguments to the function. Arguments are separated by a comma and are in the same order as in the function declaration. So numbers[0] gets passed to add() as the num1 argument, while numbers[1] is the num2 argument.

    It's really not much more complicated than that. The only thing that I don't think you mentioned is the "float" at the beginning of "float add( float num1, float num2 )". That float is there to say that the function add returns a value of type float.

    Good luck with your finals. This stuff is confusing at first, but once you "get it" it becomes interesting and you can do cool stuff with it. I'd also point out that it's worth the effort you spend on it, as unlike some other subjects you will be required to study, you will absolutely definitely use it. Also, languages other than C have very similar concepts, it's generally just the specific syntax that's different.
     
  8. bronxbomber92 macrumors regular

    Joined:
    Nov 23, 2006
    #9
    Declares the function "add" with two arguements of type float.
    Code:
    /* function prototype */
    float add( float, float);
    The definition of function "add" and specifies the name of the arguement - basically it makes what the function does
    Code:
    float add( float num1, float num2 ) {
        float sum;
        sum = num1 + num2;
    
        return sum;
    }
    Declares an array (group of variables in one memory "slot"), assigning numbers[0] to 1, numbers[1] to 2 and numbers[3] (which will eventully hold the sum of the numbers[0] and numbers[1]) to 0
    Code:
    /* declare and fill array */
    float numbers[3] = { 1, 2, 0 };
    Set numbers[2] equal to the sum of numbers[0] and numbers[1] using the function we made "add".
    Code:
      /* call function with elements 0 and 1 (the first and second) and */
      /* return the result to the third element of the array */
        numbers[2] = add(numbers[0], numbers[1]);
    edit - beat to it... :p
     
  9. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #10
    Thanks alot guys, i'm gonna get practising right away. I'll post any further problems.
     
  10. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #11
    hey guys, i think i got the hang of it a little, here's what i did so far.

    #include<stdio.h>
    int add(int a, int b);
    int mult( int c, int d);
    int div(int e, int f);
    int sub(int g,int h);
    int w,x,y,ans;

    int add( int a, int b)
    {
    int sum;
    sum = a+b;
    return sum;
    }

    int mult( int c, int d)
    {
    int pro;
    pro = c*d;
    return pro;
    }

    int div(int e,int f)
    {
    int qou;
    qou = e/f;
    return qou;
    }

    int sub(int g, int h)
    {
    int res;
    res=g-h;
    return res;
    }


    int main(void)
    {
    do
    {
    printf("\nDame un numero");
    scanf("%i",&x);

    printf("\n choose an operation by typing the appropriate number");
    printf("\n1.addition");
    printf("\n2.Multiplication");
    printf("\n3.Division");
    printf("\n4.Subtraction");
    printf("\n5.leave");
    scanf("%i",&w);

    printf("\nDame un otro numero");
    scanf("%i",&y);

    if(w==1)
    {
    ans=add(x,y);
    }
    if(w==2)
    {
    ans=mult(x,y);
    }
    if(w==3)
    {
    ans=div(x,y);
    }
    if(w==4)
    {
    ans=sub(x,y);
    }
    if(w==5)
    {
    printf("\nbye");
    }
    printf("\n%i",ans);
    }while(w=!5);
    }
     
  11. bronxbomber92 macrumors regular

    Joined:
    Nov 23, 2006
    #12
    Looking good so far (though it didn't look through it that much :p) :)
    In C though, do the declarations of function have the type and name of the arguements, or only the type like bousozoku posted above?
     
  12. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #13
    It works both ways, the way i have it and the way bousozoku had it also. I just did it for formality. Thanks again. will be posting any problems.

    ps "dame un numero"=give me a number
    "dame otro numero"= give me another number
     
  13. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #14
    I do it without names because I often put things in a header (.h) file so that the prototypes are usable over a large number of source files.
     
  14. mduser63 macrumors 68040

    mduser63

    Joined:
    Nov 9, 2004
    Location:
    Salt Lake City, UT
    #15
    Looks good. Just a quick style note though. It's generally considered good practice to go for longer variable names rather than shorter names. The extra characters don't take much longer to type, take up negligible space, but they'll make your code much more readable. Instead of using "res", use "result"; instead of using "pro" use "product", etc.
     
  15. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #16
    Thanks, you know i never even thought of it that way. But it makes perfect sense.
     
  16. Quboid thread starter macrumors 6502

    Joined:
    Oct 16, 2006
    Location:
    everywhere
    #17
    wow..i had to dig o fine this thread....

    I have two question:

    How do i work with void functions? Like calling them and so on?

    And how do i store a string, for example. A name in just one variable?

    thanks guys... got an exam tomorrow, the second class for the semester, i think the teacher just wants to check out proficiency.
     
  17. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #18
    void functions are called like any other type of function but they don't have a variable to receive a value because it doesn't return a value.

    Storing a string happens by way of a pointer and allocating (*alloc function calls) space to attach to the pointer.
     
  18. scan macrumors 6502

    Joined:
    Oct 24, 2005
    #19
    you don't need the prototype if you going to write the function before the main. just fyi...

     
  19. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #20
    That's true but he's learning, and being methodical never hurts when programming.

    It's easy to see all of the code at a glance with this short source code module. When it has hundreds of lines, it's not quite so easy to remember the prototype. If it's at the front of file, it's easy to find.
     
  20. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #21
    Speaking of learning, I've written some C under windows (mostly examples from C books while teaching myself), and now I'm on a Mac.

    I'd previously installed XCode, and just copied and pasted the first C example above. After saving it, I double-clicked it in Finder and it opened up in XCode - good so far.

    However, the BUILD options are greyed out. What's the best way to start my process of playing around with this file?

    Todd


    (EDIT: Nevermind - I figured it out.)
     
  21. scan macrumors 6502

    Joined:
    Oct 24, 2005
    #22
    Thats true... but it is because he's learning he should know how it exactly works and how it should be done.
     
  22. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #23
    Omitting the prototype is how it should be done? Really?
     
  23. scan macrumors 6502

    Joined:
    Oct 24, 2005
    #24
    If you want to write the function above the main, you can omit the prototype. When you write something like:

    prototype;

    main()

    function()

    then when it gets compiled it knows to look for the function because you made it aware of it with the prototype. I don't even believe it will get compiled if it the prototype is omitted. Reason you would do this is when your program grows big you can start organizing your program by grouping the prototypes together and the functions together.
     
  24. MarkCollette macrumors 68000

    MarkCollette

    Joined:
    Mar 6, 2003
    Location:
    Calgary, Canada
    #25
    So, how did the test go?

    A void function is just one that does not return any value. It simply does work, and then is done. You'd call it just like your add function, except there would be no variable on the left hand side being assigned the result.

    Strings, in C, are arrays of char. So, char name[100] would be a string called name which could hold at most 99 characters, plus the terminating null character, which is just a char with value zero. Strings in C don't have a means of describing how long they are, so the ending null is what tells everyone when it's done. You can put less than 99 characters in name, by simply putting the terminating null char earlier on, right when the name ends.

    Oh, and typically, what people do is they put their function prototypes (also called delcarations, at the top of a file, all together. Then they put the definitions, or the bodies of the functions, lower down, all together. This way, if you add or move functions around in the file, it will just work. And it helps if you want to move the prototypes away into a separate header file.
     

Share This Page