Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was trying to understand casting in C. I tried this code in IDEONE and got no errors at all:

#include <stdio.h>

int main(void) {

    int i=1;
    char c = 'c';
    float f = 1.0;

    double* p = &i;
    printf("%d
",*(int*)p);
    p = &c;
    printf("%c
",*(char*)p);
    p = &f;
    printf("%f
",*(float*)p);
    return 0;
}

But when compiled on C++ compiler here I got these errors:

prog.cpp:9:15: error: cannot convert 'int*' to 'double*' in initialization
  double* p = &i;
               ^
prog.cpp:11:4: error: cannot convert 'char*' to 'double*' in assignment
  p = &c;
    ^
prog.cpp:13:4: error: cannot convert 'float*' to 'double*' in assignment
  p = &f;
    ^

and this is compatible with what I know so far; that is, I can't assign (in C++) incompatible types to any pointer, only to void *, like I did here:

#include <stdio.h>

int main(void) {

    int i=1;
    char c = 'c';
    float f = 1.0;

    void* p = &i;
    printf("%d
",*(int*)p);
    p = &c;
    printf("%c
",*(char*)p);
    p = &f;
    printf("%f
",*(float*)p);
    return 0;
}

Now, if this code runs perfectly well in C, why do we need a void pointer? I can use any kind of pointer I want and then cast it when needed. I read that void pointer helps in making a code generic but that could be accomplished if we would treat char * as the default pointer, wouldn't it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Try to compile you code with a serious ANSI C compiler, from C89 to C11, and you will get the same error:

Test.c(9): error #2168: Operands of '=' have incompatible types 'double *' and 'int *'.
Test.c(11): error #2168: Operands of '=' have incompatible types 'double *' and 'char *'.
Test.c(13): error #2168: Operands of '=' have incompatible types 'double *' and 'float *'.

I suppose that the online compiler is somewhat trimmed to accept any code also pre-ansi.
C is still a weak typed language, but such errors are not accepted by actual standard level.
C++ is more strong typed language (it needs it to work), so even the online compielr gives you the error.
The need of a universal pointer, void *, is absolutely required to act as a general pointer to be interchanged.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...