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 ,
.