Monday, April 23, 2018

C Syntax Explanation

Unwind already gave you the answer, but I want to expand on it a bit.


In C, some types are not compatible; you can't directly assign a value of type T to a variable of type Q; for example, you can't assign a pointer to int to a variable that's type pointer to double:


double *q;
int *p;
...
q = p; // will cause a diagnostic to be issued

If you really need to make that assignment, though, you can use a cast expression, which converts the value to the target type:


q = (double *) p;

This tells the compiler to convert the value of p to pointer to double and assign the result to q.


In the original, K&R version of C, malloc returned char *, so if you wanted to assign the result of malloc to a pointer of a different type, you had to apply the cast:


int *p = (int *) malloc(SIZE);

That changed in 1989, when the first C standard was introduced. That version introduced a void * type to act as a "generic" pointer type. Values of type void * can be assigned to other pointer types directly, without need of a cast. So, as of C89 and later, you can simply write


int *p = malloc(SIZE);

This was not only cleaner, it was also safer; if you forgot to include stdlib.h or otherwise didn't have a declaration for malloc in scope, the compiler would assume that malloc returned an int value and generate code accordingly. Since an int value can't be directly assigned to a pointer type, you would get a diagnostic. If you added the cast, however, that warning would be suppressed, and you would potentially have issues at runtime.


The 1999 standard got rid of the implicit int assumption, so that's no longer a real danger, but it's still better style to leave the cast off of a malloc call.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...