Difference between revisions of "C language"

From Bitnami MediaWiki
Jump to navigation Jump to search
Line 64: Line 64:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
−
* Scope/Lifetime: scope applies to identifiers, lifetime applies to objects
+
* '''Scope/Lifetime''': scope applies to identifiers, lifetime applies to objects
−
* Storage duration: automatic, static, thread, allocated
+
* '''Storage duration''': automatic, static, thread, allocated
−
* Alignment: object types have restrictions on the addresses at which they may be stored. an ''alignment'' is the number of bytes between successive addresses at which a given object can be allocated. Traditionally done with linker commands or overallocating memory with <code>malloc</code>, followed by rounding the address up to nearest power of 2.  
+
* '''Alignment''': object types have restrictions on the addresses at which they may be stored. an ''alignment'' is the number of bytes between successive addresses at which a given object can be allocated. Traditionally done with linker commands or overallocating memory with <code>malloc</code>, followed by rounding the address up to nearest power of 2.  
 
* C11 sorted most of this out. Alignments are values of type <code>size_t</code>. Valid assignments are non-negative powers of 2.  
 
* C11 sorted most of this out. Alignments are values of type <code>size_t</code>. Valid assignments are non-negative powers of 2.  
  

Revision as of 21:25, 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. A variable is an example of an object. An object with type int contains and integer value. E.g. why types are important: the text number 1 in IEEE 754 (ASCII, roughly) is specified by 0x3f80000, which a little over a billion as a decimal.
  • functions: are not objects, but do have types. A function is defined by both its return type and the number and types of its parameters.
  • types: int, char, bool, float, long int...
  • pointers: an address or location in memory where an object or function is stored. Pointer types derive from the referenced function. or object type. E.g., *char is called a pointer to char.
  • Because objects and functions are different things, object pointers differ from function pointers
  • In the swap program below the main function declares two variables of type int, using the combination of a type (int), an identifier (a,b) and a value (21,17). Assigning the values is also called initialization
  • 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 (whether values or pointers)
  • pass-by-value: C's default behavior. When you provide an argument to a function, its value is copied into a distinct variable for use within that function. When the values of the parameters are changed, the values in the caller are unaffected because they are distinct objects.
#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 (*)
  • In the new version, the line *pa=*pb serves to:
  1. deference the pointer pb
  2. reads the referenced value
  3. dereference the pointer pa
  4. overwrite the value at the location referenced by pa with the value referenced by pb
  • in the main function, &a , the unary & operator (address-of operator) generates a pointer to its operand.


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; 
}
  • Scope/Lifetime: scope applies to identifiers, lifetime applies to objects
  • Storage duration: automatic, static, thread, allocated
  • Alignment: object types have restrictions on the addresses at which they may be stored. an alignment is the number of bytes between successive addresses at which a given object can be allocated. Traditionally done with linker commands or overallocating memory with malloc, followed by rounding the address up to nearest power of 2.
  • C11 sorted most of this out. Alignments are values of type size_t. Valid assignments are non-negative powers of 2.
struct S {
  int i; double d; char c;
};
int main(void) {
  unsigned char bad_buff[sizeof(struct S)];
  _Alignas(struct S) unsigned char good_buff[sizeof(struct S)];
  struct S *bad_s_ptr = (struct S *)bad_buff;   // wrong pointer alignment
  struct S *good_s_ptr = (struct S *)good_buff; // correct pointer alignment
}

In the above code

Object Types
  • Boolean: declare as bool; contains either 0 or 1. (Also denoted _Bool
  • Character: char, signed char, unsigned char
  • Numeric: signed char, short int, int, long, long long int. For each there is a corresponding unsigned type that uses the same amount of storage (but obviously only 1/2 the range on the positive side).
  • Enumerations: allows type definition by assigning names ("enumerators") to integer values. E.g., {S,M,T,W,Th,F,Sa}
  • Floating-point: float, double, long double.
  • void: the keyword void means "cannot hold any value". However, void * means the pointer can reference any object.
Function Types
  • types are all derived. Name and return type are specified by the function declarator. Parameter types must be specified unless of type void
int max(int a, int b)
{ return a > b ? a : b; }
  • Here is a function that returns an int. The declarator is max(int a, int b) and the function body is the 2nd line
  • The function specification (line 2) may not include any type qualifiers (e.g., int, char, etc.)
  • Derived Types: pointers, arrays, type definitions, structures and unions
  • Pointers: derived from the function or object it points to, which is the referenced type. E.g., int i= 17; int *ip = &i;,

declares the variable ip as a pointer to int and assigns it the address of i. The unary * operator converts a pointer to a type into a value of that type. Consider ip = &*ip;. Here * is dereferencing ip. It takes the address using & and retrieves the pointer.

  • Arrays: contiguously allocated sequence of objects of the same type. E.g. int ia[11], float *afp[17];.