Reputation: 560
Is there a way to to something like:
char* a = "Hello";
char* b = NULL;
char* c = a | b;
Result should be c = "Hello";
Seems like it does not work with Char*, but is there a way to do something like that?
Upvotes: 0
Views: 95
Reputation: 464
It is possible using ternary operators. The code below sets c to b if a == NULL and sets c to a otherwise.
char *c = (a == NULL)? b : a;
Now a clarification on bitwise operators: | and & work on the bits of the operands. Suppose we have two variables, a = 10000001 (128) and b = 10000010 (129). It does not matter the type of a and b, only the bit representation of their values.
a | b = 10000011, that is, it takes the bitwise OR between the bits of a and b;
a & b = 10000000, that is, it takes the bitwise AND between the bits of a and b;
These operators make sense when you are working directly with the bits of the value of your variables. In C, the value of a pointer is the address of a chunk of memory, not the contents of its chunk. Applying a bitwise operation on pointers means applying a bitwise operation on the addresses that they hold. The result of this operation can point to almost anywhere on the memory and using this pointer will probably get you a Segmentation Fault (or at least junk data).
Upvotes: 1
Reputation: 724
This is nonsense not only because bitwise operators on pointers would have very... interesting... results, but mainly because NULL is not guaranteed to be represented by 0.
Upvotes: 1
Reputation: 781716
The following will set c
to a
if it's not null, otherwise set it to b
:
char *c = a ? a : b;
This is called the ternary operator.
Upvotes: 0