1

As you can see from the code, to extract a string from a function I used two methods, the first one is to use a pointer and the second one to use a global array. Both have the same result, but I wanted to know if it is a mistake to use one or the other, since they advised me not to use the globals without giving me an explanation.

forgive my ignorance, unfortunately I have no one to ask and in the search engines I have not found someone who would deal with this topic.

#include <stdio.h>
#include <string.h>

char MyArr[18] = {'\0'}; // Global Array //


// This function use a *Pointer //
const char * MyWordWP( void )
{

    return "Hello with pointer";
}



// This function use a global array  //
void MyWordArr( void )
{
     strcpy(MyArr, "Hello With Array");   

}



int main( void )
{
// Read pointer  //
    const char *MyW = MyWordWP( );
    printf( "With Pointer =  %s \n" , MyW );

//Set the global //
    MyWordArr();
    printf( "With Array = %s \n", MyArr);


    return 0;
}

Thank you for your support.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
ExagonX
  • 141
  • 10
  • 1
    The global array methode is very bad practice. It results in less readable and less maintainable code, it is not thread safe, it has absolutely no advantage and certainly a few other reasons I forgot to mention. Generally it's a good idea to have as few global variables as possible – Jabberwocky Apr 20 '20 at 11:00
  • Global array will occupy memory till program terminates. But it maybe it is not used always in the program so it is better not not use global array but its correct you can use for learning and testing small programs. – Ankit Mishra Apr 20 '20 at 11:04
  • @AnkitMishra Thank you for explanation. I generally don't use global arrays, but if the values of an array are called and modified by multiple functions during program execution, for example a current status that must be updated according to the function that operates. Throughout the program there may be 2 or 3 global variables or arrays. – ExagonX Apr 20 '20 at 12:07
  • 1
    This is a very good, but also [commonly asked question](https://stackoverflow.com/questions/2216340/the-advantage-disadvantage-between-global-variables-and-function-parameters-in). There are times when globals are the right thing to do, but more often passing arguments is the better approach. – ryyker Apr 20 '20 at 12:39

2 Answers2

2

A few reasons why to not use global objects and arrays too extensively are for example:

First, Functions which use global objects are not very reusable. Identifiers are hard-coded in the source code. This makes the use of the function almost unique which is generally not the best solution. In contrary, parameters allow to pass values from objects of different identifiers and in the case of pointers also addresses from arrays of different sizes.

The same goes for the opposite process of returning values and pointers from functions, like in your case. Note, that inside of a function an object must be declared with the storage class specifier static to remain in memory after the end of the function´s execution, which is important in case of returning a pointer to a function-local object.

The string literal "Hello With Array" exists beyond the execution of the function MyWordArr() because string literals reside in memory until the program finishes.

Second, your code may become hard to read and maintain for others but also for yourself when the source code is very large and f.e. after a few hundred function calls you lost a bit of the exquisite overview and may ask yourself: "What is the function actually doing?" - whereas opposed to that, passed parameters and return values describe the intention and the context of the use of a function call pretty good.

Third, the object can be accessed from almost anywhere in the code, making it hard to find the cause of an unintentional modification in a large program.

Fourth, global objects are not thread-safe.


So as conclusion:

It depends upon the case of use. In your provided example it might fit well as the program is small and focused, but generally you shall try (if it is possible) to avoid global objects because production code is in most cases very large and tend to be brain smashing on its own.

  • Well, so I can use a global variable if the function only serves to reduce lines of code like setting or changing the name of a file. – ExagonX Apr 20 '20 at 14:39
  • 2
    @ExagonX You *can* use global variables when- and wherever you like (where it is possible of course). It is more a matter of style to choose which way to go. More people will advice you to not use or to use global variables as less as possible but there is nothing wrong about it if you do different. It can be beneficial in cases, when several functions access a specific object and are also only made to access that specific object for its role in the code. But as a general rule, *try*, and I said only, *try* to avoid them for the provided reasons. – RobertS supports Monica Cellio Apr 20 '20 at 14:47
  • Thanks RobertS This is a Usefull advice, the peoples who advised me against using globals did it without explaining why. – ExagonX Apr 20 '20 at 16:35
  • @ExagonX I´m glad that I could help you out. – RobertS supports Monica Cellio Apr 20 '20 at 18:18
1

Maybe a good reason to use a global variable, either array or pointer, is when there are one or more functions that always use that (global) variable, and this is coded into the logic. In such case, you would end up with a program full of calls to "func(myvar);" when the logic is that func() always should read or update that variable "myvar".

An example could be a text console driver or library, where a cache of the screen is kept in memory. The application calls setcursorto(x,y), display("hello"), color(yellow) and so on; all these routines update the cache in memory: well, that cache should be a global variable and there is no need to pass that global variable to every function operating on it.

Regarding the visibility, not all the global variables have to be visible to all the program. A C source file can have static global variables not visible outside.