What is the equivalent of C++ '*&' in C ?. Does it even exist? - c++

for example, how to implement this C++ code in C ?
void someFunction(type *&outParamOnly) ;
returnType someOtherFunction() ;
...
returnType someOtherFunction()
{
type *data = NULL ;
someFunction(data) ;
...
}
...
void someFunction(type *&outParamOnly)
{
bool condition ;
int array_len ;
...
if(condition) // variable's value passed to this function stays as it was
return ;
...
outParamOnly = new type[array_len] ; // value is moddified and it's reflected in 'someOtherFunction'
...
}
...
I'm asking because I don't know how to create such equivalent. Does it's complex ?. In fact I don't know much about C, but much more about C++ syntax, etc. I'm used to write in C++ and once I tryied C to feel diffrence I'm not doing well when trying to implement what I want. I expect positive answer - that it possible to create some equivalent,
but will it be running faster then in C++ or slower ?
Please answer.

The nearest equivalent is a pointer to a pointer; **. C doesn't have references.
There is a slight difference in the call and the function; you must send a pointer to the variable and dereference it when you want to use it:
void someFunction(type **outParamOnly)
...
*outParamOnly = whatever;
}
someFunction(&data);
This is a fairly typical pattern in C.

You'll need to change the function to accept a pointer-to the thing to be modified. In this case, since the value is a pointer, you'll need to declare the function to accept a double-pointer.
Then, when calling the function, pass the address of the value to be modified.
someFunction(&data) ;
...
void someFunction(type **outParamOnly)
{
*outParamOnly = whatever;
Or, you could return the value from the function instead of returning void.

C has no reference types, so there's no easy "equivalent" for the syntax you are asking about.
One can use a pointer-to-pointer to emulate that behavior. I'm not sure if that's the appropriate solution, though. Why not just return the value instead of messing around with various levels of pointers if it's an output argument anyway?

C doesn't have references, but the equivalent is just 'type **'.
void someFunction(type **outParamOnly)
{
if( NULL != outParamOnly )
*outParamOnly = new type[array_len] ;
}
returnType someOtherFunction()
{
type *data = NULL ;
someFunction(&data) ;
}
Note that you need the extra dereference when assigning to what's pointed by outParamOnly and you need to pass a pointer to data when calling someFunction.

Related

Why can't we use a void* to operate on the object it addresses

I am learning C++ using C++ Primer 5th edition. In particular, i read about void*. There it is written that:
We cannot use a void* to operate on the object it addresses—we don’t know that object’s type, and the type determines what operations we can perform on that object.
void*: Pointer type that can point to any nonconst type. Such pointers may not
be dereferenced.
My question is that if we're not allowed to use a void* to operate on the object it addressess then why do we need a void*. Also, i am not sure if the above quoted statement from C++ Primer is technically correct because i am not able to understand what it is conveying. Maybe some examples can help me understand what the author meant when he said that "we cannot use a void* to operate on the object it addresses". So can someone please provide some example to clarify what the author meant and whether he is correct or incorrect in saying the above statement.
My question is that if we're not allowed to use a void* to operate on the object it addressess then why do we need a void*
It's indeed quite rare to need void* in C++. It's more common in C.
But where it's useful is type-erasure. For example, try to store an object of any type in a variable, determining the type at runtime. You'll find that hiding the type becomes essential to achieve that task.
What you may be missing is that it is possible to convert the void* back to the typed pointer afterwards (or in special cases, you can reinterpret as another pointer type), which allows you to operate on the object.
Maybe some examples can help me understand what the author meant when he said that "we cannot use a void* to operate on the object it addresses"
Example:
int i;
int* int_ptr = &i;
void* void_ptr = &i;
*int_ptr = 42; // OK
*void_ptr = 42; // ill-formed
As the example demonstrates, we cannot modify the pointed int object through the pointer to void.
so since a void* has no size(as written in the answer by PMF)
Their answer is misleading or you've misunderstood. The pointer has a size. But since there is no information about the type of the pointed object, the size of the pointed object is unknown. In a way, that's part of why it can point to an object of any size.
so how can a int* on the right hand side be implicitly converted to a void*
All pointers to objects can implicitly be converted to void* because the language rules say so.
Yes, the author is right.
A pointer of type void* cannot be dereferenced, because it has no size1. The compiler would not know how much data he needs to get from that address if you try to access it:
void* myData = std::malloc(1000); // Allocate some memory (note that the return type of malloc() is void*)
int value = *myData; // Error, can't dereference
int field = myData->myField; // Error, a void pointer obviously has no fields
The first example fails because the compiler doesn't know how much data to get. We need to tell it the size of the data to get:
int value = *(int*)myData; // Now fine, we have casted the pointer to int*
int value = *(char*)myData; // Fine too, but NOT the same as above!
or, to be more in the C++-world:
int value = *static_cast<int*>(myData);
int value = *static_cast<char*>(myData);
The two examples return a different result, because the first gets an integer (32 bit on most systems) from the target address, while the second only gets a single byte and then moves that to a larger variable.
The reason why the use of void* is sometimes still useful is when the type of data doesn't matter much, like when just copying stuff around. Methods such as memset or memcpy take void* parameters, since they don't care about the actual structure of the data (but they need to be given the size explicitly). When working in C++ (as opposed to C) you'll not use these very often, though.
1 "No size" applies to the size of the destination object, not the size of the variable containing the pointer. sizeof(void*) is perfectly valid and returns, the size of a pointer variable. This is always equal to any other pointer size, so sizeof(void*)==sizeof(int*)==sizeof(MyClass*) is always true (for 99% of today's compilers at least). The type of the pointer however defines the size of the element it points to. And that is required for the compiler so he knows how much data he needs to get, or, when used with + or -, how much to add or subtract to get the address of the next or previous elements.
void * is basically a catch-all type. Any pointer type can be implicitly cast to void * without getting any errors. As such, it is mostly used in low level data manipulations, where all that matters is the data that some memory block contains, rather than what the data represents. On the flip side, when you have a void * pointer, it is impossible to determine directly which type it was originally. That's why you can't operate on the object it addresses.
if we try something like
typedef struct foo {
int key;
int value;
} t_foo;
void try_fill_with_zero(void *destination) {
destination->key = 0;
destination->value = 0;
}
int main() {
t_foo *foo_instance = malloc(sizeof(t_foo));
try_fill_with_zero(foo_instance, sizeof(t_foo));
}
we will get a compilation error because it is impossible to determine what type void *destination was, as soon as the address gets into try_fill_with_zero. That's an example of being unable to "use a void* to operate on the object it addresses"
Typically you will see something like this:
typedef struct foo {
int key;
int value;
} t_foo;
void init_with_zero(void *destination, size_t bytes) {
unsigned char *to_fill = (unsigned char *)destination;
for (int i = 0; i < bytes; i++) {
to_fill[i] = 0;
}
}
int main() {
t_foo *foo_instance = malloc(sizeof(t_foo));
int test_int;
init_with_zero(foo_instance, sizeof(t_foo));
init_with_zero(&test_int, sizeof(int));
}
Here we can operate on the memory that we pass to init_with_zero represented as bytes.
You can think of void * as representing missing knowledge about the associated type of the data at this address. You may still cast it to something else and then dereference it, if you know what is behind it. Example:
int n = 5;
void * p = (void *) &n;
At this point, p we have lost the type information for p and thus, the compiler does not know what to do with it. But if you know this p is an address to an integer, then you can use that information:
int * q = (int *) p;
int m = *q;
And m will be equal to n.
void is not a type like any other. There is no object of type void. Hence, there exists no way of operating on such pointers.
This is one of my favourite kind of questions because at first I was also so confused about void pointers.
Like the rest of the Answers above void * refers to a generic type of data.
Being a void pointer you must understand that it only holds the address of some kind of data or object.
No other information about the object itself, at first you are asking yourself why do you even need this if it's only able to hold an address. That's because you can still cast your pointer to a more specific kind of data, and that's the real power.
Making generic functions that works with all kind of data.
And to be more clear let's say you want to implement generic sorting algorithm.
The sorting algorithm has basically 2 steps:
The algorithm itself.
The comparation between the objects.
Here we will also talk about pointer functions.
Let's take for example qsort built in function
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
We see that it takes the next parameters:
base − This is the pointer to the first element of the array to be sorted.
nitems − This is the number of elements in the array pointed by base.
size − This is the size in bytes of each element in the array.
compar − This is the function that compares two elements.
And based on the article that I referenced above we can do something like this:
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
Where you can define your own custom compare function that can match any kind of data, there can be even a more complex data structure like a class instance of some kind of object you just define. Let's say a Person class, that has a field age and you want to sort all Persons by age.
And that's one example where you can use void * , you can abstract this and create other use cases based on this example.
It is true that is a C example, but I think, being something that appeared in C can make more sense of the real usage of void *. If you can understand what you can do with void * you are good to go.
For C++ you can also check templates, templates can let you achieve a generic type for your functions / objects.

Assigning an assignment in C++

I'm reading a piece of code which does this
void *ptr_to_something = (void*)0x23; // I made this up, it's just a pointer to something
void *addr;
void *dst = (void*)(addr = ptr_to_something); // This is the line that confuses me
it seems to assign a pointer to something to another pointer of the same thing. And that's okay.. but then the result is enclosed in parenthesis, cast to the same thing and somehow reassigned to a third pointer to the same thing.
Is this valid C++ at all? Is it guaranteed that assigning the result of an assignment yields the same assigned object?
It is valid in C++ to do:
int a, b, c;
a = b = c = 1;
So, therefore the result of an assignment is the value of that assignment.
What the cast is for, is a mystery*. Have you tried removing it, and does that generate a warning?
*not a mystery, just perhaps unnecessary.
This is valid C++. The choice to format the code this way is odd and not advised, but it's perfectly legal.
This code is equivalent to this (what I consider to be better written) code:
void *ptr_to_something = (void*)0x23;
void *addr = ptr_to_something;
void *dst = addr;

How can a function pointer replace switch statement?

I am reading this tutorial about function pointers which said that function pointers can replace a switch statement
http://www.newty.de/fpt/intro.html .
Can anyone clarify?
We have a switch statement like this:
// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
// Execute example code
void Replace_A_Switch()
{
cout << endl << "Executing function 'Replace_A_Switch'" << endl;
Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
As you can see, the Replace_A_Switch() function as an example is very unclear. Supposed we need to point the function pointer to one of 4 arithmetic functions(Plus,Mins,Multiply,Divide). how can we know which one we need to point to? We have to use the switch statement again to point the function pointer to the arithmetic functions , right?
It will be like this one**(please the comment in the code)**:
void Replace_A_Switch()
{
.....................
..........
//How can we know this will point to the &Minus function if we don't use the switch statement outside?
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
So in summary, what is the advantages of function pointer, it always said that the function pointer a late-binding mechanism , but in this tutorial i dont see any advantage of the function pointer for late binding.
Any help are very appreciated. Thanks.
What you're saying is pretty well true, you still need to decide somewhere what function pointer to use.
What you're looking at though is a pretty simple, contrived example for explanation purpose. It shows how you can leverage a function pointer. In this case it might be pointlessly complicated but a real case would probably be too complicated to use to instruct in this basic concept.
The difference becomes much clearer when you've got a lot of functions that have the same switch, or a switch with subsets of the same set. The difference is all the same though (this is also important). In that case, why rewrite it a bunch of times?
It also opens your code for a change in how the decision is made. Maybe you want to invert '+' and '-' for whatever reason. Change the point where you make the pointer and all the client code catches up.
Finally, what if you don't even need to make the decision? Instead of replacing the switch for example, what if you just wanted to do the addition version? Obviously addition is too simple a task for this level of design, but again it's just an example.
All this is true whether you're using function pointers or a class hierarchy. Someone has to decide what the input will be. What these constructs do is provide you a method to compose different bits into a running program. It also separates the part that is responsible for deciding which version of things to use from the using of those things. There are a lot of different ways to approach that creation (see creational design patterns for some).
As the tutorial states there are no advantages and the basic calculator is simply an example. The main use of function pointers is to allow the API-dev to define a function, which does something that is not known at the time the API is created.
A better example is probably qsort, which takes a comparison function. Thanks to this function-pointer argument it is possible to implement the sort in a generic way. Since you could not possibly know what kind of data needs to be sorted you can't know how the <,=,> operators have to be implemented. Thus you expect the caller to provide a function that implements the comparison thereby avoiding this dilemma.
In general, function pointers are often useful if you want to program something in a generic way. Its use is that of function-arguments in other languages. If someone asked you to implement a simple reduce function for example, you could come up with something like this:
void reduce(void *data, size_t nmemb, size_t size,
void (*op)(void *, void *), void *res){
int i;
for (i = 0; i < nmemb; ++i){
op(data, res);
data = (void *)((unsigned char*)data + size);
}
}
Clearly it is very advantageous over rewriting this for operations like multiply, add, and more complex ones all over again with the respective function replacing op.
I can see how you can convert your '+', '-' etc into an enum, and store the 4 func pointers into an array ordered by the enum order. After that arr[op] is the function you want, just execute that.
Alternatively a std::map<String, FuncType> map from + -> &Plus.
as from what i see..
the pt2Func is a name defined for pointer which references a function
you can see how it works in the main where it is being called
(removed the comment to make it more readable)
Switch_With_Function_Pointer(2, 5, &Minus);
&Minus here is a pointer that references to your function Minus
this is stupid as you are calling a function to reference another function by using a pointer.
There is no benefit and it does nothing special.. its just another more complicated way to call the Minus function
the Switch function however is just a normal switch encapsulated in a function for reusability

Convert void* to a dynamic type

I have a double variable i, that is converted to a void pointer named pointer:
double i = 3;
void *pointer = &i;
When I like to convert the void pointer back to double I used:
double p = *((double*) pointer);
I would like to convert the void pointer to the type I will send as a char*:
char* myType= typeid(i).name();//get the name of type of "i"
int p = *((myType*) pointer); // how to implement?
Is it possible?
instead of
char* myType= typeid(i).name();//get the name of type of "i"
int p = *((myType*) pointer); // how to implement?
use
typedef decltype(i) myType;
myType p = *((myType*) pointer);
or better:
typedef decltype(i) myType;
auto p = *reinterpret_cast<myType*>(pointer);
Works with c++11 or later. If you want to decltype on older c++ compilers, it is emulated in boost.
Edit. This is probably different from what you wanted to do, which I suppose is something like this:
void myFunction(void* unknownParam) {
typedef (realTypeOf unknownParam) RealType; // <-- this is not real c++
RealType &a = *reinterpret_cast<RealType*>(unknownParam)
//do stuff using 'a'
}
This is not possible in C++, but there is a reason: it doesn't make much sense.
And the reason is that for myFunction to be valid the //do stuff using 'a' part should be valid for whatever type RealType ends up being. As such, it cannot rely on any feature the RealType type have: it cannot use any of its methods, it cannot use any operator, it cannot even know whether it is a class or not. Basically, you cannot do anything more with it than what you would already be able to do on a void*, so giving the type a name doesn't really help you much.
A language feature that is similar to what you want (but not quite it) is type reflection, which is not present in C++, but you can find it in language such as Java, Objective-C or C#. Basically, you ask the object itself if it has a certain method, and eventually call it. An example in Objective-C
-(void)myFunction:(id)unknownParam {
if([unknownParam respondsToSelector:#selector(myMethod)])
[unknownParam performSelector:#selector(myMethod)]
}
C/C++ does not work well to interchange datatype like for example JavaScript variables
Format of int value will be different than double value format (floating point) in binary
You cannot get original data type using typeid after it has been casted to void*. Also note that typeid will have different output on different OS and compilers
double dValue = 77.7;
void* pValue = &dValue;
//output "pV" / pointer void (depending on compiler and OS)
std::cout << typeid(dValue).name() << std::endl;
To cast from void* using string you can make rules like following. Or you can try to use C++ template functions in specific cases.
int iOutValue = 0;
double dOutValue = 0;
char* name = "double";
if(!strcmp(name, "int"))
{
iOutValue = *((int*)pValue);
}
else if(!strcmp(name, "double"))
{
dOutValue = *((double*)pValue);
}
If instead of passing around void* you used some kind of variant type, you would be able to convert it back.
If you use a string to indicate the type you will need some kind of map from string to actual type. Although you can go from type to string, there is no conversion back.
Assuming you know your underlying data is always numeric in some way, there are ways to have special discrete variants that only contain numbers. The simplest would be to store a union of a 64-bit int and a double, and some flag indicating which one you have, and then a method to convert to any numeric type, asDouble(), asLong() etc.

Why would *&param be used in a function?

I've been trying to make sense of LLVM's instruction combining code and noticed this function:
static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
if (!Op->hasOneUse())
return;
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
if (!II)
return;
if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
return;
Log2 = II;
Value *OpLog2Of = II->getArgOperand(0);
if (!OpLog2Of->hasOneUse())
return;
Instruction *I = dyn_cast<Instruction>(OpLog2Of);
if (!I)
return;
if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
return;
if (match(I->getOperand(0), m_SpecificFP(0.5)))
Y = I->getOperand(1);
else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Y = I->getOperand(0);
}
Why would *& by used in the parameters? Does it have some meaning or would Op be equivalent to *&Op?
Why would *& by used in the parameters?
In a function parameter list, this parameter
IntrinsicInst *&Log2
is a reference to pointer to Value. It means the function can modify the pointer itself, and this is seen at the caller side. In this case, that happens here:
Log2 = II;
If Log2 was not passed by reference, the above line would only have an effect in the scope of the function.
... would Op be equivalent to *&Op?
Not in this context. In a different one, yes. For example, when * is the de-reference operator and & is the address-of operator, then *&x would mean "de-reference the result of applying the address-of operator to x", that is, de-reference a pointer to x. C++ confusingly re-uses symbols depending on context. Most of this is inherited from C. On top of that, changes to C++ should not break existing code. The easiest way to do this is to re-use symbols.
& means reference.
value * means value is a pointer.
value *&op is equalent to passing pointer by reference, so if we change value in the function it will be reflected in the called function.