0

Why so many brackets?!

#include <stdio.h> void * square (const void *num); int main() { int x, sq_int; x = 6; sq_int = square(&x); printf("%d squared is %d\n", x, sq_int); return 0; } void* square (const void *num) { static int result; result = (*(int *)num) * (*(int *)num); return(result); } This is from the function pointers lesson in C. What the?! Why is there so many brackets at the bottom. This entire thing makes no sense!

24th Jun 2020, 11:20 AM
Clueless Coder
Clueless Coder - avatar
7 ответов
+ 2
I see.. Anyway IMHO the example is not very good, since the current Playground compiler complains the absence of 2 casts, in line sq_int = square(&x); ...it must be: sq_int = (int)square(&x); and in line return(result); ... it must be: return (void *)result; Furthermore, even adding the two casts - again in current Playground compiler which is 64bit - we must be careful, since we are casting from 64 to 32 bits and viceversa
24th Jun 2020, 12:21 PM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
In fact there is no reason for square() to take "const void *" as argument and return "void *" as result; all this as a collateral effect forces to use confusing casts. The whole thing can be simplified as: #include <stdio.h> int square (int num) { return num*num; } int main() { int x, sq_int; x = 6; sq_int = square(x); printf("%d squared is %d\n", x, sq_int); return 0; }
24th Jun 2020, 11:51 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
~ swim ~ Sorry for asking again. I'm having some issues with this code https://code.sololearn.com/caZnuh2493H2/?ref=app I've been trying for a while and I just can't get it right. I was hoping I'd get used to C by practicing but it's just winding me up. Also thanks for your answer.
24th Jun 2020, 12:25 PM
Clueless Coder
Clueless Coder - avatar