Search code examples
cpointersgcc

Pointer of number in C


Assume there's function that get int * parameter.

void foo(int *x)
{
    
}

If I want to call this function without creating an int variable

int main()
{
    foo(&1);
    return 0;
}

compilation fails and I get this error message:

lvalue required as unary ‘&’ operand

Why 1 has no address? Isn't that stored in stack ?


Solution

  • Why 1 has no address? Isn't that stored in stack ?

    No - it is just a value.

    You need an object to take its address (reference). A constant expression is not such an object.

    You can use compound literals to create temporary object:

    void foo(int *x)
    {
        printf("%d\n", *x);
    }
    
    int main(void)
    {
        foo( (int[]){1} );
        foo( &(int){1} );
    }
    

    https://godbolt.org/z/xvdbTzn3Y

    but string constants have addresses what is the difference ?

    They are not constant expressions only string literals. String literal is an array of char``[C] or const char``[C++]. String literals cannot be modified (it invokes undefined behabior) . It is an object and you can take the address of it:

    void foo(char (*x)[])
    {
        printf("'%s'\n", *x);
    }
    
    int main(void)
    {
        foo(&"dsfgdfsgdfg");
    }
    

    https://godbolt.org/z/q9s3P6xcb