简体   繁体   English

C中函数的返回值

[英]Return value of a function in C

I tried writing some code to check if the paranthesis in an expression are balances using the below function. 我尝试编写一些代码来检查表达式中的paranthesis是否使用以下函数进行平衡。 Can someone help me understand why the below function is returning 1 in case of a balanced expression when it's not specified anywhere to return 1. 有人可以帮助我理解为什么下面的函数在平衡表达式的情况下返回1,而在任何地方都没有指定返回1。

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

struct Stack
{
    int top;
    unsigned capacity;
    char* array;
};

struct Stack* createStack (unsigned capacity)
{
    struct Stack* stack = (struct Stack*) malloc (sizeof(struct Stack));
    if(!stack)
        return NULL;

stack->top = -1;
stack->capacity = capacity;
stack->array = (char*) malloc(stack->capacity * sizeof(int));

if (!stack->array)
    return NULL;
return stack;
}

int isEmpty(struct Stack* stack)
{
    return (stack->top == -1);
}
void push(struct Stack* stack, char op)
{
    stack->top++;
    stack->array[stack->top] = op;

}

int pop(struct Stack* stack)
{

    if (!isEmpty(stack))
        return (stack->array[stack->top--]);
    return '$';
}

int isMatchingPair(char char1 , char char2)
{
    if (char1 == '(' && char2 == ')')
        return 1;
    else if (char1 == '[' && char2 == ']')
        return 1;
    else if (char1 == '{' && char2 == '}')
        return 1;
    else
        return 0;
}

int paranthesesMatch(char* exp)
{
    int i;
    struct Stack* stack = createStack(strlen(exp));
    for(i = 0; exp[i]; i++)
    {
        if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
        push(stack , exp[i]);
       if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
       {
        if (stack == NULL)
            return 0;
        else if ( !isMatchingPair(pop(stack), exp[i]) )
           return 0;

       }
    }
}

int main()
{
  char exp[100] = "{()}[)";
  printf(" %d\n", paranthesesMatch(exp));
  if (paranthesesMatch(exp) == 1)
    printf("Balanced \n");
  else
    printf("Not Balanced \n");  
   return 0;
}  

Edit: Added the full code. 编辑:添加完整代码。

Your function returning 1 is the result of undefined behavior. 返回1函数是未定义行为的结果。 The compiler is free to do whatever it desires, because not all execution paths in your function yield a return statement. 编译器可以随心所欲地执行任何操作,因为并非函数中的所有执行路径都会产生return语句。

The reason it may appear to work is that the caller (that is unaware that the function finished without a return statement), tries to access the returned value (which may be in a designated register). 可能会出现工作的原因是调用者(也就是不知道该函数没有return语句结束),尝试访问返回值(这可能是在指定的寄存器)。 And your function modifies said register before returning to the caller. 并且您的函数在返回调用者之前修改了所述寄存器。

Bumping up your warning levels when building, will produce a diagnostic about it ( like so ). 在构建时提高警告级别将产生关于它的诊断( 如此 )。 You should consider promoting that particular warning to an error, since omitting a return statement can result in sinister and hard to find bugs. 您应该考虑将该特定警告提升为错误,因为省略return语句可能导致险恶且难以发现错误。

why the below function is returning 1 in case of a balanced expression when it's not specified anywhere to return 1. 为什么下面的函数在平衡表达式的情况下返回1,当没有指定返回1时。

Your function has branches of code that do not return a value at all. 您的函数具有完全不返回值的代码分支。 Specifically, when the loop reaches the end, your function does not specify what to return. 具体来说,当循环到达结尾时,您的函数不会指定要返回的内容。 In situations like that using function's return value is undefined behavior: whatever the function appears to "return" is a junk left-over value that could be different on different computers, or even on the same computer when you run the program multiple times. 在使用函数的情况下,返回值是未定义的行为:无论函数出现什么,“返回”都是一个垃圾剩余值,在不同的计算机上可能会有所不同,甚至在多次运行程序时也可能在同一台计算机上。

As far as the function itself goes, the NULL check for a stack is probably incorrect, unless the code deletes the stack once it's empty (which would be a rather poor decision). 就函数本身而言,堆栈的NULL检查可能是不正确的,除非代码在它为空时删除stack (这将是一个相当糟糕的决定)。 In addition, the code has a memory leak, because stack is never freed. 此外,代码有内存泄漏,因为stack永远不会被释放。 It also over-allocates stack->array content by a factor of sizeof(int) (4 on many computers these days): 它还以一个sizeof(int)因子过度分配stack->array内容(这些天在许多计算机上为4):

stack->array = (char*) malloc(stack->capacity * sizeof(int));

should be 应该

stack->array = malloc(stack->capacity);

because you make a stack of char s, not a stack of int s. 因为你创建了一堆char ,而不是一堆int

Finally, there is no need to allocate stack dynamically. 最后,不需要动态分配stack Allocate an array of char s, and make a "stack pointer" or stack index to point at the beginning of your stack. 分配一个char数组,并使“堆栈指针”或堆栈索引指向堆栈的开头。 Increment and decrement the pointer/index when you push/pop elements onto the stack. 将元素推送/弹出到堆栈时递增和递减指针/索引。 If you use a variable-length array, you wouldn't need to clean up dynamically allocated memory. 如果使用可变长度数组,则无需清理动态分配的内存。

Ah as reference to this remember this.. Flowing off the end of a function is same as a return with no expression. 啊,作为对此的参考,请记住这一点。函数结束时的流程与没有表达式的返回相同。 In either of this case, the return value is undefined. 在任何一种情况下,返回值都是未定义的。

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

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