所以目前我正在尝试测试的if函数中有一个GetNth语句。但是当我插入一个printf函数时,它使我注意到即使不满足条件,它也会通过if语句,但是,当我删除printf语句时,该程序可以正常工作。任何解释将不胜感激。

注意!这不是我的代码,我试图学习链接列表,并且正在更改尝试学习的代码!

代码:

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

/* Link list node */
struct node
{
    int data;
    struct node* next;
};

/* Given a reference (pointer to pointer) to the head
 of a list and an int, push a new node on the front
 of the list. */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
    (struct node*) malloc(sizeof(struct node));

    /* put in the data  */
    new_node->data  = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Takes head pointer of the linked list and index
 as arguments and return data at index*/
int GetNth(struct node* head, int index)
{
    struct node* current = head;
    int count = 0; /* the index of the node we're currently
                    looking at */
    int a;
    while (current != NULL)
    {
        if (count == index)
            return(current->data);
            a = current->data;
            printf("\n Testing If in linked list, should bring same desired value which is 4 %d \n ",a);
        count++;
        current = current->next;
    }

    /* if we get to this line, the caller was asking
     for a non-existent element so we assert fail */
    assert(0);
}

/* Drier program to test above function*/
int main()
{
    /* Start with the empty list */
    struct node* head = NULL;

    /* Use push() to construct below list
     1->12->1->4->1  */
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
    if (head != NULL)
    {

    }
    /* Check the count function */
    printf("Element at index 3 is %d", GetNth(head, 3));
    getchar();
}

最佳答案

缺少括号。

这就是为什么我是“始终添加括号”的捍卫者的原因。

编辑“解决方案”。

当前代码是:

while (current != NULL)
{
    if (count == index)
        return(current->data);
        a = current->data;
        printf("\n Testing If in linked list, should bring same desired value which is 4 %d \n ",a);
    count++;
    current = current->next;
}


如果不使用大括号,则if语句仅适用于下一条指令,即return(current->data);

如果要在if块中包含多个指令,则必须创建一个带有花括号的块。

if (count == index)
{
        return(current->data);
        a = current->data;
        printf("\n Testing If in linked list, should bring same desired value which is 4 %d \n ",a);
}


但是,您从返回指令开始,因此以下两行将永远不会执行。

重新排列说明以在退货前打印。

if (count == index)
{
     a = current->data;
     printf("\n Testing If in linked list, should bring same desired value which is 4 %d \n ",a);
     return(current->data);
}

07-24 09:46
查看更多