nalzok
nalzok

Reputation: 16107

Returning pointer to static local variable

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

Upvotes: 0

Views: 98

Answers (2)

R Sahu
R Sahu

Reputation: 206567

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())++;

Upvotes: 6

Haris
Haris

Reputation: 12270

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()))++;

Upvotes: 2

Related Questions