0

When I compile this code,

#include <stdio.h>

int *foo();

int main()
{
        *foo()++;
        return 0;
}

int *foo()
{
        static int bar;
        return &bar;
}

Clang shows me an error:

static2.c:7:8: error: expression is not assignable

Why it's illegal? I suppose bar have static storage duration, so its lifetime is the entire execution of the program. Although bar itself isn't visible to main(), a pointer should be able to modify it.

This version of foo() doesn't work too, and Clang gives me the same error:

int *foo()
{
    static int bar;
    static int* ptr = &bar;
    return ptr;
}

2 Answers 2

6

Due to operator precedence (suffix increment, ++, is higher than dereference, *) (See http://en.cppreference.com/w/cpp/language/operator_precedence),

    *foo()++;

is equivalent to:

    *(foo()++);

That is invalid since the return value of foo is a pointer and foo() evaluates to a temporary pointer. You cannot increment or decrement a temporary pointer.

You can fix it by using:

    (*foo())++;
Sign up to request clarification or add additional context in comments.

Comments

2

Its illegal because of the way you are using the return value. bar is visible and can be used in main()

The problem is with

*foo()++;

You need to provide the expression in parentheses

(*(foo()))++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.