简体   繁体   English

在C中返回局部变量混乱

[英]Returning a local variable confusion in C

Recently I read a thread on stackoverflow that returning a local variable must be avoided whether its a pointer type or a normal variable. 最近,我在stackoverflow上读到一个线程,该线程必须避免返回本地变量,无论该指针是指针类型还是普通变量。 I saw an example in my C book and it was returning a local variable, so I thought to try it again 我在C书中看到了一个示例,它返回一个局部变量,所以我想再试一次

#include <stdio.h>
int func(int a, int b)
{
    int d, e, f;
    d = a;
    e = b;
    f = d+e;
    return f;
}
int main(void)
{
    int c = func(1, 2);
    printf("hello\n");//I put this printf in between
    printf("c = %d\n", c);//here c should be overwritten
    return 0;
}

In that thread it was said, that if I put anything between function call and accessing that variable, I will miss the value. 在那个线程中,有人说,如果我在函数调用和访问该变量之间放置任何内容,我将丢失该值。

I am able to access the local variable whatever I do, yet I recall I wrote an example according to that thread and was showing same behaviour as told. 我可以执行任何操作来访问局部变量,但是我记得我根据该线程编写了一个示例,并且显示出与所指示的相同的行为。

What am I missing? 我想念什么?

The unnamed thread you mentioned has mislead you. 您提到的未命名线程误导了您。

In your example, func() is returning an integer. 在您的示例中,func()返回一个整数。 Returning an integer is always safe, regardless of where it came from. 无论整数来自何处,返回整数始终是安全的。

Values (int, char, double) are never shared. 值(int,char,double)从不共享。 Each time you pass/return them, a copy of that value is passed/returned, so it is safe. 每次传递/返回它们时,都会传递/返回该值的副本,因此很安全。

Pointers (int*, char*, double*) can share the memory location they are pointing at. 指针(int *,char *,double *)可以共享它们指向的内存位置。 Passing/returning them can be dangerous, because the value at that memory location will change over time. 传递/返回它们可能很危险,因为该存储位置上的值会随着时间变化。 You have to be careful with pointers. 您必须小心使用指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM