C language
Revision as of 17:33, 18 March 2022 by 98.152.106.150 (talk)
Elements of C
#include <stdio.h>
void swap(int *pa, int *pb) {
int t = *pa;
*pa = *pb;
*pb = t;
// int t = a;
//a = b;
//b = t;
printf("swap: a = %d, b = %d\n", *pa,*pb);
}
int main(void){
int a = 21;
int b = 17;
swap(&a, &b);
printf("main: a = %d, b = %d\n", a, b);
return 0;
}
The commented lines in the swap function show the original program, which failed to swap main's values, because they were being passed by value rather than reference. The corrected version (above) declares and dereferences pointers with the indirection operator (*).
void increment(void) {
static unsigned int counter = 0;
counter++;
printf("%d", counter);
}
int main(void) {
for (int i = 0; i < 5; i++) {
increment();
}
return 0;
}