Home > Mobile >  Effect of casting in a C program
Effect of casting in a C program

Time:09-14

I somehow understand the idea about casting, but still have the following questions about it, when we cast a variable from one type to another:

  1. Does casting change the actual data type generally? Like eg. if we have char *name ="james" and we cast the char pointer ==> int *name = (int *) name
  2. Do the types of all fields (members) also change in case of a structure data type in C? I.e. if we have a struct student {int id, char *name} and there is a pointer to an instance of struct student and type cast it to another type, do the fields also change?

CodePudding user response:

casting (also called type coercion) does not change the data - the underlying bits - but it changes the type, i.e., how those bits are interpreted.

I could take 65, which is 01000001 in binary and say, "this is an int". If I interpret it as a char in ASCII encoding, it represents the letter 'A'.

Casting a pointer type changes what is expected to be at the pointer target. A pointer just points to an address in memory and the type also encodes how many bytes you expect at that destination.

E.g., On my system, pointers may be 64bit large, int * might point to a 32bit integer. If I cast it to char * and we assume char to be 1 byte and we derefference the pointer to read, then we'd only read 1 byte from that 4 byte int.

Ad 2.: By now it should be clear, that casting a pointer will not change the underlying data of what you point to. It will change the interpretation. Casting a pointer to a struct and then using it may work if the structs layouts and underlying data are compatible, but it also may return gibberish or crash.

TL;DR: Casting is not conversion. It just changes the interpretation of the underlying data without changing the data itself. Casting a pointer does not touch the data the pointer points to.

CodePudding user response:

From another answer here,

casting (also called type coercion) does not change the data - the underlying bits - but it changes the type, i.e., how those bits are interpreted.

In other words, a cast tells the compiler:

"You would think the expression has this type, but I say you to use the expression as it had this different type"

At this point the compiler says "Ok" and compile code to do what you ask for with the cast. Take this example (probably there are better ones):

int a,b;
int *p;

a=256;  // does not fit in a single byte
p=&a;   // a pointer to a
b=*p;   // <- now b is 256, the value of a
b=*(char *) p;  // <- now b is 0 (probably)

The two assignments to "b" are different. In the first case the compiler nows that p points to integers, so it will move in b 4 or 8 bytes taken from a.

The second assignment, with the cast, tells the compiler to act as p was not a pointer to an integer, but a pointer to a char. And the compiler obeys, and takes only one byte from the value of a (pointed to by p).

  • Related