返回C中的局部变量混乱 [英] Returning a local variable confusion in C

查看:86
本文介绍了返回C中的局部变量混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在stackoverflow上读到一个线程,该线程必须避免返回局部变量,无论该变量是指针类型还是普通变量.我在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. I saw an example in my C book and it was returning a local variable, so I thought to try it again

#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.

我想念什么?

推荐答案

您提到的未命名线程误导了您.

The unnamed thread you mentioned has mislead you.

在您的示例中,func()返回一个整数.无论整数来自何处,返回整数始终是安全的.

In your example, func() is returning an integer. Returning an integer is always safe, regardless of where it came from.

从不共享值(int,char,double).每次您传递/返回它们时,都会传递/返回该值的副本,因此很安全.

Values (int, char, double) are never shared. Each time you pass/return them, a copy of that value is passed/returned, so it is safe.

指针(int *,char *,double *)可以共享它们所指向的内存位置.传递/返回它们可能很危险,因为该存储位置的值会随着时间而变化.您必须小心使用指针.

Pointers (int*, char*, double*) can share the memory location they are pointing at. Passing/returning them can be dangerous, because the value at that memory location will change over time. You have to be careful with pointers.

这篇关于返回C中的局部变量混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆