C -> Typecasting

Unter »Typecasting« versteht man die Typumwandlung einer Variablen oder eines Zeigers eines bestimmten Typs (zB int) in einen anderen Typ (zB float) um vorübergehend eine höhere Genauigkeit zu erreichen oder um zwei Objekte vorübergehend zueinander kompatibel zu machen:

Man unterscheidet prinzipiell zwischen der »impliziten« und »expliziten« Typumwandlung.

Implizite Typumwandlung

Eine implizite Typumwandlung wird nicht im Code vorgenommen, sondern wird vom Compiler automatisch erkannt und entsprechend durchgeführt. Eine »implizite« Typumwandlung kann nur von kleinen zu großen Datentypen erfolgen, wie im folgenden Beispiel:

implizite Typumwamdlung

#include <stdio.h>
 
int main() {
 
  int i = 5;
  float f = i; //implizite Typumwamdlung von int nach float
   {
     printf(" %d\n %f\n",i,f);
   }
  return 0;
}

Die Ausgabe zeigt sich wie folgt:

$ ./cast_1
 5
 5.000000

Explizite Typumwandlung

Bei der »expliziten« Typumwandlung wird die Typumwandlung im Code vorgenommen. Es gilt dabei folgende Syntax: »(Zieltyp)Ausdruck«, wobei »Zieltyp« der Datentyp ist, zu dem »Ausdruck« konvertiert werden soll.

pointer_types_1

#include <stdio.h>
 
int main() {
	int i;
 
	char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
	int int_array[5] = {1, 2, 3, 4, 5};
 
	char *char_pointer;
	int *int_pointer;
 
	char_pointer = char_array;
	int_pointer = int_array;
 
	for(i=0; i < 5; i++) { 
		printf("[integer pointer] points to %p, which contains the integer %d\n", int_pointer, *int_pointer);
		int_pointer = int_pointer + 1;
	}
 
	for(i=0; i < 5; i++) { 
		printf("[char pointer] points to %p, which contains the char '%c'\n", char_pointer, *char_pointer);
		char_pointer = char_pointer + 1;
	}
}

$ ./pointer_types_1 
[integer pointer] points to 0xbfa86134, which contains the integer 1
[integer pointer] points to 0xbfa86138, which contains the integer 2
[integer pointer] points to 0xbfa8613c, which contains the integer 3
[integer pointer] points to 0xbfa86140, which contains the integer 4
[integer pointer] points to 0xbfa86144, which contains the integer 5
[char pointer] points to 0xbfa86157, which contains the char 'a'
[char pointer] points to 0xbfa86158, which contains the char 'b'
[char pointer] points to 0xbfa86159, which contains the char 'c'
[char pointer] points to 0xbfa8615a, which contains the char 'd'
[char pointer] points to 0xbfa8615b, which contains the char 'e'

tux/typecasting.txt (3783 views) · Zuletzt geändert: 2011/11/30 20:02 von wikisysop
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0