C:没有显式返回构造的结构,但是它仍然有效 [英] C: Not explicitly returning constructed struct, but it still works

查看:84
本文介绍了C:没有显式返回构造的结构,但是它仍然有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个构造函数",该函数使用Visual Studio 2008和ANSI C模式编译而成的C语言中的节点.

I write a 'constructor' function that makes a Node in C, compiled with Visual Studio 2008, ANSI C mode.

#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
  struct _node* next ;
  char* data ;
} Node ;

Node * makeNode()
{
  Node * newNode = (Node*)malloc( sizeof(Node) ) ;

  // uncommenting this causes the program to fail.
  //puts( "I DIDN'T RETURN ANYTHING!!" ) ;
}

int main()
{
  Node * myNode = makeNode() ;
  myNode->data = "Hello there" ;

  // elaborate program, still works

  puts( myNode->data ) ;

  return 0 ;
}

令我惊讶的是

  • *不从makeNode()返回值只是警告,
  • *更令人惊讶的是,只要我不放置任何东西,makeNode()__仍能正常工作!

这是怎么回事,执行此操作可以"(不返回您在C构造函数"函数中创建的对象吗?)

What's going on here and is it "ok" to do this (not return the object you create in a C 'constructor' function?)

为什么它仍在工作?为什么puts()命令会导致程序失败?

WHY is it still working? Why does the puts() command cause the program to fail?

推荐答案

不返回任何内容的原因是警告而不是错误,这在很大程度上可能是历史原因.在传统" C语言中,函数无需声明其返回类型(默认为int).有些函数编写时没有明确的返回类型,并且没有返回任何内容,其他函数则选择返回有意义的内容,但仍未声明返回类型.试图收紧返回语句或缺少返回语句将意味着破坏许多旧式代码.

The reason that not returning anything is a warning and not an error is probably largely historical. In 'traditional' C, functions didn't need to declare their return type which just defaulted to int. Some functions were written with no explicit return type and didn't return anything, others chose to return something meaningful but still didn't declare a return type. Trying to tighten up return statements or lack thereof would have meant breaking a lot of old-style code.

它可能会起作用,但是您看到的内容取决于无法保证的事情.

It might happen to work, but what you are seeing is dependent on things which aren't guaranteed.

可能发生的是,函数的返回值进入特定的寄存器.调用malloc之后,如果您什么也不做,并且函数结束了,则malloc返回的内容似乎由您的函数返回,因为结果仍然位于该函数调用之后的返回寄存器中.

What's probably happening is that the return value of a function goes into a particular register. After you call malloc, if you do nothing else and fall of the end of the function, what is returned by malloc appears to be returned by your function as the result is still sitting in the return register after that function call.

如果调用其他函数,则malloc的返回值将丢失,并且函数返回的结果将是返回寄存器中所发生的一切.

If you call some other function, the return value of malloc is lost and what is returned by your function is whatever happened to end up in the return register.

这篇关于C:没有显式返回构造的结构,但是它仍然有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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