Functions in C

functions.c

#include <stdio.h>

/* Declaration of the function. Things to notice:
 * 1) The body of the function will come after main
 * 2) Argument names do not need to be the same as the
 * names of the variables, with which the function is 
 * called in the main.
 * 3) First argument is **passed by value**, thus the modifications
 * made inside foo function are visible ONLY inside the function.
 * 4) Second argument is **pased by reference**, thus the modifications
 * made inside foo function are visible inside and outside (that is in
 * main too) the function. That's the reason it has a star (*) after its
 * data type. Into main we need to fetch the variable with a &.
 */
void foo(int argumentOne, int* argumentTwo);

int main(void)
{
    int a, b;
    a = 5;
    b = 10;
    
    printf("Before the function call, a = %d and b = %d\n", a, b);
    
    foo(a, &b);
    
    printf("AFTER the function call, a = %d and b = %d\n", a, b);
    
    return 0;
}

/* Definition of function foo. */
void foo(int argumentOne, int* argumentTwo)
{
    argumentOne = 1500;
    *argumentTwo = 32000; /* We need the star (*) */
}

// OUTPUT will be
Before the function call, a = 5 and b = 10
AFTER the function call, a = 5 and b = 32000

// also we could call another function and still the idea remains the same
void bla(int* argumentTwo)
{
  *argumentTwo = 32000;
}


/* Definition of function foo. */
void foo(int argumentOne, int* argumentTwo)
{
    argumentOne = 1500;
    bla(argumentTwo);
}

This code was developed by me, G. Samaras.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

8 thoughts on “Functions in C

  1. Pingback: Size of Linked List

  2. Pingback: 2nd scanf input problem.

  3. Pingback: Defining a new function in C programming.

  4. Pingback: Values are not calculating?

  5. Pingback: Help with single word Palindrome

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s