Difference between revisions of "C language"
Jump to navigation
Jump to search
| Line 22: | Line 22: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| − | The commented lines in the <code>swap</code> function show the original program, which failed to swap <code>main</code>'s values. | + | The commented lines in the <code>swap</code> function show the original program, which failed to swap <code>main</code>'s values, because they were being passed by value rather than reference. The corrected version (above) declares and dereferences pointers with the '''indirection''' operator (*). |
Revision as of 17:33, 18 March 2022
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;
}