2

I was doing this program from Hackerrank in C and I solved the program without declaring my character array 'result' as static. It returned an error where my Output didn't match with the Expected Output. But as soon as I inserted the keyword 'static' in the declaration of the array 'result', the code ran successfully.

Here is my code snippet:

char* timeConversion(char* s) 
{
    int i;
    static char result[100];      // this doesn't work if i remove the word 'static'
    if (s[0]=='1' && s[1]=='2' && s[8]=='A')
        { 
            result[0]='0';
            result[1]='0';
            for (i=2;i<8;i++)
               result[i]=s[i];  
        }
    else if (s[0]=='1' && s[1]=='2' && s[8]=='P')
        for (i=0;i<8;i++)
               result[i]=s[i];
    else
    {
       if (s[8]=='A')
           for (i=0;i<8;i++)
               result[i]=s[i];
       if (s[8]=='P')
       {
           result[0]=s[0]+1;
           result[1]=s[1]+2;
           for (i=2;i<8;i++)
               result[i]=s[i];           
       }        
     }
    return result; 
}

I don't understand that, what is the use of Static here?

2
  • 1
    If your read your text-book, what does it say about local static variables? Commented Aug 22, 2018 at 4:31
  • 1
    Static variable exist during all lifetime of a program also it’s save it value between function call, local variable exist only during function work. That’s why it doesn’t work when you remove keyword static, you return local variable. Also please read about static it’s has another meaning in some case, for functions or for global scope variable Commented Aug 22, 2018 at 4:52

3 Answers 3

2

Two things:

  1. You are returning the address of a stack-allocated array from your function. If it were not static, you'd just be returning the address of an array that doesn't exist anymore since ordinarily, objects on the stack disappear when they go out of scope (i.e. when the function returns). To return an array from a function that can actually be used by the calling code, it must either be allocated on the heap (i.e. with malloc) or be declared static, since local variables in functions that are declared with the static qualifier persist after the function returns.

  2. If a variable without the static qualifier is declared but not initialized explicitly, it just gets whatever's already in memory at the time.

    If a local variable or array is declared with the static qualifier, it is implicitly initialized with zeroes. This means that the variable result can be populated with the parsed date/time value and is guaranteed to be a null-terminated string since all the elements of the array that aren't populated by the code in the function are already zero.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok. So if don't use the word 'static', then when I return from the function, the array goes out of scope i.e. the main() doesn't find any such array having the address I just returned. But if I use the word 'static', then the array persists in the memory even after the command returns to main(), and hence the main() can access the array. Is this the case?
@RajdeepDutta Pretty much.
1

C11 6.2.2 Linkages of identifiers(P3):

If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.30)

Footnote:

30) A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.

It means static variable is declared once and its life time is entire execution of the program. That's why return static array working fine in your code, which makes sense.

If you remove static keyword, then array become a local or auto and scope of local variable exists only within the block or function that it is declared in. in your code, you are trying to return local array, that's invoked undefined behaviour.

GCC Compiler warning :

In function 'timeConversion':
prog.c:30:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return result;
            ^~~~~~

Comments

1

I don't understand that, what is the use of Static here?

A couple of meanings of static relevant to your program, taken from C99 standard (N1256):

6.2.4 Storage durations of objects

  1. An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated. Allocated storage is described in 7.20.3.

  2. The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,25) and retains its last-stored value throughout its lifetime.26) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

  3. An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

6.7.8 Initialization
....
10. If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;
if it has arithmetic type, it is initialized to (positive or unsigned) zero;
if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

So, in your example, static specifies the lifetime of the result array and also initializes the array as per the rules highlighted above.

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.