Function
Pass by value
#include <stdio.h>
void doubleNum(int n)
{
printf("In fuction: %d, %p\n", n, &n);
n *= 2;
printf("In fuction: %d, %p\n", n, &n);
}
int main()
{
int a = 10;
printf("Value: %d, Address: %p\n", a, &a);
doubleNum(a);
printf("After calling function: %d, %p\n", a, &a);
}
Pass by reference
#include <stdio.h>
void doubleNum(int *n)
{
printf("In fuction: %d, %p\n", *n, n);
*n *= 2;
printf("In fuction: %d, %p\n", *n, n);
}
int main()
{
int a = 10;
printf("Value: %d, Address: %p\n", a, &a);
doubleNum(&a);
printf("After calling function: %d, %p\n", a, &a);
}
Layout in single file
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int doubleNum(int n)
{
int num;
num = 2*n;
return num;
}
int main()
{
srand(time(NULL)); // take a random seed
int r = rand()%100; // generate a random number within [0, 100)
printf("Value: %d\n", doubleNum(r));
}
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int doubleNum(int);
int main()
{
srand(time(NULL)); // take a random seed
int r = rand()%100; // generate a random number within [0, 100)
printf("Value: %d\n", doubleNum(r));
}
int doubleNum(int n)
{
int num;
num = 2*n;
return num;
}
Layout in multiple files
// f3.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "util.h"
int main()
{
srand(time(NULL)); // take a random seed
int r = rand()%100; // generate a random number within [0, 100)
printf("Value: %d\n", doubleNum(r));
}
// util.c
#include "util.h"
int doubleNum(int n)
{
int num;
num = 2*n;
return num;
}
// util.h
#ifndef UTIL_H
#define UTIL_H
int doubleNum(int);
#endif