Home > Blockchain >  Address of a Variable assigned to integer varaiable.How?
Address of a Variable assigned to integer varaiable.How?

Time:01-04

address of a variable is assigned to integer variable without an error(just a warning) in C Language.how is this possible?? Can Anyone explain? Code:

int main()
{
    int a=9;
    int *x=&a;
    int y=&a;
    printf("%d\n",y);
    printf("%p",x);
    return 0;
}

OUTPUT of the code:

test.c: In function 'main':
test.c:7:11: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
       int y=&a;
           ^
6422292
0061FF14

I am expecting an error in storing of address in integer variable.

CodePudding user response:

how is this possible?? … I am expecting an error in storing of address in integer variable.

int y=&a; violates the constraints for simple assignment in C 2018 6.5.16.1 1, which list several combinations of types allowed for the right operands. The only combination in which the left operand has arithmetic type other than _Bool, as int does, says the right operand must also have arithmetic type, which &a does not:

… the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type…

C 2018 5.1.13 1 says what a conforming C implementation must do for this:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint,…

A warning is a diagnostic message. Therefore it satisfies the requirements of the C standard. This answers your question “how is this possible?”

Enable warnings in your compiler and elevate warnings to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /WX.

CodePudding user response:


  • without an error(just a warning)

    There is no such thing as "just a warning". A warning typically means: "here is a severe bug which you must fix to make your program behave as intended". It does not typically mean: "here is some minor cosmetic issue which you can ignore".



  • Related