Difference between revisions of "C language"

From Bitnami MediaWiki
Jump to navigation Jump to search
Line 1: Line 1:
 
==Elements of C==
 
==Elements of C==
 +
Sources
 +
* [http://robertseacord.com/wp/errata/ Effective C ]by Robert Seacord
 +
* 21st Century C
 +
*
 +
 +
===Basics===
 +
;Objects, Functions, Types and Pointers
 +
* object: storage used to represent values. (Per ISO/IEC 9989:2018: "a region of data storage in the execution environment, the contents of which can represent values. '''Variables''' are examples of objects. An object with '''type''' <code>int</code>
 +
* parameters: objects declared as part of a function declaration that acquire value on entry to the function
 +
* argruments: comma-separated expressions included in the function call expression
 +
* pass-by-refernce
 +
 
<syntaxhighlight lang=C>
 
<syntaxhighlight lang=C>
 
#include <stdio.h>
 
#include <stdio.h>
Line 23: Line 35:
  
 
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 (*).  
 
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 (*).  
 +
 +
* pass-by-value:
  
  

Revision as of 17:43, 18 March 2022

Elements of C

Sources

Basics

Objects, Functions, Types and Pointers
  • object: storage used to represent values. (Per ISO/IEC 9989:2018: "a region of data storage in the execution environment, the contents of which can represent values. Variables are examples of objects. An object with type int
  • parameters: objects declared as part of a function declaration that acquire value on entry to the function
  • argruments: comma-separated expressions included in the function call expression
  • pass-by-refernce
#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 (*).

  • pass-by-value:



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; 
}