Why so many brackets?! | Sololearn: Learn to code for FREE!


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!

6/24/2020 11:20:02 AM

Clueless Coder

7 Answers

New Answer


Clueless Coder You have already typedef anonymous struct to person, so struct person* will now be seen as another type (anonymous struct) just write person* in function parameter list if you write typedef struct person{ char name[50]; int age; } person; then you can write struct person* in function parameter list.


Bilbo Baggins The example is from 'Functions using void pointers" section in the course, hence it is not about simplefication.


Bilbo Baggins Yes the compiler does give warnings. the correct code should be sq_int = *(int*)square(&x); and in the function return &result; // as any pointer is implicitly convertible to void* in C. Personally i would have done return (void*)&result.


At the best you can write this result = *(int*)num * *(int*)num; but this can be confusing to some due to presence of '*' '*' in vicinity of each other the purpose of using extra brackets is to tell two separate numbers are being multiplied. Rest all brackets are necessary.


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


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; }


~ 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.