开发者

Is there any point in declaring pointers for variables that are on the stack?

 void my_c开发者_StackOverflow中文版ool_function() 
 {
   obj_scene_data scene;
   obj_scene_data *scene_ptr = &scene;
   parse_obj_scene(scene_ptr, "test.txt");
 }

Why would I ever create a pointer to a local variable as above if I can just do

 void my_cool_function() 
 {
   obj_scene_data scene;
   parse_obj_scene(&scene, "test.txt");
 }

Just in case it's relevant: int parse_obj_scene(obj_scene_data *data_out, char *filename);


In the specific code you linked, there isn't really a reason.

It could be functionally necessary if you have a function taking an obj_scene_data **. You can't do &&scene, so you'd have to create a local variable before passing the address on.


Yes absolutely you can do this for many reasons.

For example if you want to iterate over the members of a stack allocated array via a pointer.

Or in other cases if you want to point sometimes to one memory address and other times to another memory address. You can setup a pointer to point to one or the other via an if statement and then later use your common code all within the same scope.

Typically in these cases your pointer variable goes out of scope at the same time as your stack allocated memory goes out of scope. There is no harm if you use your pointer within the same scope.

In your exact example there is no good reason to do it.


If the function accepts a NULL pointer as input, and you want to decide whether to pass NULL based on some condition, then a pointer to a stack variable is useful to avoid having to call the same function in separate code paths, especially if the rest of the parameters are the same otherwise. For example, instead of this:

void my_function()  
{ 
    obj_data obj = {0}; 
    if( some condition )
        other_function(&scene, "test.txt"); 
    else
        other_function(NULL, "test.txt"); 
} 

You could do this:

void my_function()  
{ 
    obj_data obj = {0}; 
    obj_data *obj_ptr = (condition is true) ? &obj : NULL;
    other_function(obj_ptr, "test.txt"); 
} 


If parse_obj_scene() is a function there may be no good reason to create a separate pointer. But if for some unholy reason it is a macro it may be necessary to reassign the value to the pointer to iterate over the subject data.


Not in terms of semantics, and in fact there is a more general point that you can replace all local variables with function calls with no change in semantics, and given suitable compiler optimisations, equal efficiency. (see section 2.3 of "Lambda: The Ultimate Imperative".)

But the point of writing code to communicate with the next person to maintain it, and in an imperative language without tail call optimisation, it is usual to use local variables for things which are iterated over, for automatic structures, and to simplify expressions. So if it makes the code more readable, then use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜