0

While debugging a program that other people wrote I encountered a strange string assignment. At first I was surprised that it even compiles. Here is an example, which compiles without warnings on Linux (Ubuntu, CentOS).

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

using namespace std;

int main ()
{
  string a;
  char b[40];

  a = "Constant value", strncpy (b, a.c_str (), sizeof (b));
  printf ("a = %s\n", a.c_str ());
  printf ("b = %s\n", b); 

  a = "Constant value";
  strncpy (b, a.c_str (), sizeof (b));
  printf ("a = %s\n", a.c_str ());
  printf ("b = %s\n", b);
}

Can someone explain, what exactly does the first string assignment in the example, and where can I find any reference describing this behaviour? As you can see a is assigned a constant string, but after that there is a comma (,) and strncpy function call, which returns char *. Why is comma accepted there? According to output it does not make a difference if I use ; or ,.

nobody
  • 64
  • 5
  • 15
  • 5
    [What does the comma operator , do?](https://stackoverflow.com/a/18444099/1708801) – Shafik Yaghmour Nov 14 '18 at 06:32
  • 4
    ["How does the comma operator work?"](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) – WhozCraig Nov 14 '18 at 06:32
  • Note that `strncpy`, carelessly used as it is here, isn't any "safer" than a plain `strcpy`; it just moves the crash on an over-length string to some other place. If you're going to use `strncpy` (which you should only rarely do; it's not intended as a general string copy), read and digest its [documentation](https://en.cppreference.com/w/cpp/string/byte/strncpy). – Pete Becker Nov 14 '18 at 14:53

1 Answers1

1

"," represents an operator. The order of "," is from left to right, for example, the value of (A, B, C) is C. ";" represents the end of a sentence. The execution sequence of the sentence has not changed, so the result is the same.

Drake Wu
  • 6,927
  • 1
  • 7
  • 30