C中函数的返回值

san*_*ank 2 c stack return return-type return-value

我尝试编写一些代码来检查表达式中的paranthesis是否使用以下函数进行平衡.有人可以帮助我理解为什么下面的函数在平衡表达式的情况下返回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;
}  
Run Code Online (Sandbox Code Playgroud)

编辑:添加完整代码.

Sto*_*ica 5

返回1的函数是未定义行为的结果.编译器可以随心所欲地执行任何操作,因为并非函数中的所有执行路径都会产生return语句.

其原因可能出现的工作是调用者(也就是不知道该函数没有return语句结束),尝试访问返回值(这可能是在指定的寄存器).并且您的函数在返回调用者之前修改了所述寄存器.

在构建时提高警告级别将产生关于它的诊断(如此).您应该考虑将该特定警告提升为错误,因为省略return语句可能导致险恶且难以发现错误.