gpt4 book ai didi

C函数调用作为测试条件

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:02 25 4
gpt4 key购买 nike

几天前,我想到了一个奇怪的想法,那就是操纵 if();以一种奇怪的方式声明。让我们继续一个简单的代码。

代码:

if(printf("blahblah\n");{  
}


我的想法:

1.) 对我来说,我认为这段代码将始终被评估为真(我的假设),因为测试条件被函数调用所取代。



所以今天我在做一个书上提供的练习(只是为了帮助我复习前几天学到的东西)。这是代码。

代码:

#include <stdio.h>

int main(void) // This program would add up the value enter by user , for e.g with the
{ //input of 20 , it will print out the sum of 1+2+3+4+5.....20.

int count , sum , size;

count = 0;

sum = 0;

printf("Enter a value to find the sum of it from 1 : ");
scanf("%d" , &size);

while (count++ < size)

sum = sum + count;

printf("sum = %d\n" , sum);

return 0;
}



根据我对第一个代码的想法,我将第二个代码修改成这样。

#include <stdio.h>

int main(void)
{
int count , sum , size;

count = 0;

sum = 0;

printf("Enter a value to find the sum of it from 1 : ");

while (scanf("%d" , &size) && count++ < size )

sum = sum + count;

printf("sum = %d\n" , sum);

return 0;
}

问题:

1.)根据我在第一个代码中所做的假设,scanf()函数假设总是被评估为真。这就是为什么第二个测试条件 count++ < size是确定 while 中的语句是否存在的那个是否执行语句。

2.)但是当我运行程序时,我输入了 30 但它不起作用,在我按下回车后程序就停止了,没有做任何事情。

3.)我尝试将 `count++ < size 作为左操作数,而将输入函数作为右操作数来切换测试条件。

4.)这样做之后,我得到的结果是不同的。当我尝试运行程序时,程序执行第二个printf()。函数语句,并打印出sum = 0 .

非常感谢您的帮助,请指正我的错误。我愿意从中吸取教训。

最佳答案

To me I think this code will always evaluated to be true(my assumption) since the test condition is substituted with a function call.

这是不正确的。该函数(在本例中为 printf)返回一个值(在本例中为 int)。当您将它用作 if 语句中的条件时,该函数将被调用并且它返回的值成为条件:如果它返回零,则计算结果为 false;如果它返回非零值,则计算结果为真。

没有区别

if (printf("Hello, World!")) { }

int i;
i = printf("Hello, World!");
if (i) { }

(当然,除了第二个例子中的附加变量。)


在您修改的第二个示例中,每次检查循环条件时都会调用 scanf。您可以像这样重写循环:

while (1)
{
int result_of_scanf;

result_of_scanf = scanf("%d", &size);
if (result_of_scanf == 0)
break;

if (count++ >= size)
break;

sum += count;
}

scanf 不仅仅被调用一次;循环的每次迭代都会调用它。 scanf 返回它成功读取的元素数,因此在这种情况下它将返回 1(如果您输入了 int< 范围内的有效整数) 或 0(如果您提供任何其他输入)。

关于C函数调用作为测试条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com