所以目前我在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();
}
答案 0 :(得分:3)
缺少牙箍。
这就是为什么我是“永远添加大括号”的捍卫者。
编辑“解决方案”。
目前的代码是:
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);
}
但是,您从返回指令开始,因此永远不会执行以下2行。
在返回之前重新排列指令以进行打印。
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);
}
答案 1 :(得分:1)
首先,即使条件为假,它也不会进入select count(*) total_by_value, value, s1.full_avg, s1.full_total
from ratings r,
(select avg(value) full_avg, count(*) full_total from ratings) s1
group by s1.full_avg, s1.full_total, value;
。
if statement
语句只考虑if语句后的紧接下一个语句。
If
如果statement为true,它只考虑return语句。
如果statement为false,则转到if (count == index)
return(current->data);
之后的下一个语句
即
;
这就是你觉得if语句不起作用的原因。
如果你需要在if循环中使用 a = current->data;
printf("\n Testing If in linked list, should bring same desired value which is 4 %d \n ",a);
,你需要在if循环中使用多个语句的语法。即通过花括号
printf