0

I'm working on some C code. In one of .c files I can see something like:

char* test = ("someChar", "someChar2", 3);

When I print out this variable, I get "3" on my screen.

What is happening in this part of code? Why do I get 3 as a result of printing out this char*? I am the most curious about this ("someChar", "someChar2", 3) expression.

EDIT(after the issue has been resolved):

What made me scratch my head was also the fact, that there are two chars and one int in this expression. If we use printf("%u", test) we can get this number, but this code definitely doesn't look clean and I believe this is not an elegant way of assigning number to char*.

Paradowski
  • 719
  • 1
  • 13
  • 17

1 Answers1

3

Its because of comma operator & manual page of operator says when in an expression if multiple comma are there then solve from Left to Right but it considers right most argument.

In the statement

char* test = ("someChar", "someChar2", 3);

test get assigned with right most argument that is 3. And now it looks like

char *test = 3;

since test is char pointer & it should initialize with valid address and 3 is not the valid address. So if you are just printing test like printf("%d\n",test); that doesn't cause any error but that causes undefined behavior. And if you are going to dereference it like *test then your program get crashed(Seg. fault), this is one of possible scenario you should keep in mind while dealing with pointers.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • 1
    printing a char* with `%d` is still undefined behavior – cleblanc Jun 06 '18 at 14:04
  • yup @cleblanc agree. I thought of writing it but forgot to put it. modified. – Achal Jun 06 '18 at 14:07
  • Thank you for explanation. To make things clear: the int value enclosed in my post in this assignment is not there by mistake. However I don't know why the original programmer put there this integer. – Paradowski Jun 06 '18 at 14:23
  • Welcome !! May be original programmer wanted to know whether one understood comma operator correctly or not. But you should be aware of all possible scenario specially with pointers. – Achal Jun 06 '18 at 14:27