Home > database >  Printing a string in C without declaring a variable
Printing a string in C without declaring a variable

Time:08-13

I've couldn't find an already existing source for this so I've come to ask here. If you know a good source that I can refer to please let me know it by comments.

Looking at many textbooks and tutorials, a way to print a string is as follows.

#include <stdio.h>

int main(void)
{
  char hello[] = "Hello, Stack Overflow";
  printf("%s\n", hello);

  return 0;
}

However, I find the following method gives me no problem.

#include <stdio.h>

int main(void)
{
  printf("%s\n", "Hello, Stack Overflow");

  return 0;
}

The latter method works just fine in my VSCode and in an online compiler as JDoodle. For me, the latter method seems to be much more intuitive and time efficient.

Why would someone use the former one if the latter one is possible?

I could guess there might be some memory management problem, if there is really any problem. Or there could be some issue of version control which I'm not sure of.

Looking forward to someone's advice. Thanks.

CodePudding user response:

There's two reasons for defining strings as separate char* or char[] variables:

  • You want control over which message is displayed at runtime.
  • You want to be able to manage the display strings from a centralized location, without having to scour through the code for instances where they're used.

For the first example:

printf("%s\n", messages[n]);

printf("%s\n", cond ? cond_true_msg : cond_false_msg);

Where that comes from a table of possible messages, or is based on a decision.

The second case is more a case of code organization, like you'll often see this:

char *SUCCESS_MSG = "Your account is now active!";
char *SUSPENDED_MSG = "Your account is suspended!";
// :
// (Hundreds of other messages used throughout the application)

// ... Much later, or perhaps in another source file entirely.

printf("%s\n", SUCCESS_MSG); // Don't care what message is, just print

This can make localization significantly easier, among other things.

When refactored or expanded in scope, this lends itself to loading in a simple "locale lookup table" for the messages themselves as you see formalized in things like iOS applications, among many other systems.

  • Related