返回C中的局部变量混乱

编程入门 行业动态 更新时间:2024-10-27 10:27:57
本文介绍了返回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中的局部变量混乱

本文发布于:2023-07-29 08:24:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   局部   混乱

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!