C语言 变量前面的!运算符是什么意思?

anauzrmj  于 2022-12-22  发布在  其他
关注(0)|答案(4)|浏览(389)

我有一个简单的问题,我正在学习C编程,我知道!运算符表示逻辑非,我的问题是,在这个例子中,do while循环作为一个条件,它是不是检查变量是否被改变了?
我知道我可能会找到它,但当我试图谷歌'!的它不想显示我的意思。

#include <stdio.h>

int main() {
    int input, ok=0;
    do {
        scanf("%d", &input);
        if ( /* condition */) {
            //the input is wrong it will scan another one
        }
        else {
            //the input is correct, so the while cycle can stop
            //we don't need more inputs
            ok = 1;
        }
    } while (!ok);

    //...
    //...
    //...

    return 0;
}
jpfvwuh4

jpfvwuh41#

!okok == 0相同。
记住在C语言中,布尔上下文中的 any 非零标量值表示“true”,而零表示“false”。常见的C语言习惯是用!foo代替foo == 0。它也适用于指针:

FILE *foo = fopen( "some_file", "r" );
if ( !foo )
{
  fprintf( stderr, "could not open some_file\n" );
  return EXIT_FAILURE; 
}

因此,while ( x )while ( x != 0 )相同,while ( !x )while ( x == 0 )相同。

a9wyjsp7

a9wyjsp72#

不严格地说,给定的代码重复执行循环的内容“while NOT ok”,意思是“while OK为零”。在else块中,ok设置为1,意思是循环不再重复。
更正式地说,!ok是一个表达式,当ok等于0时为真,当ok是除0之外的任何值时为假。

m1m5dgzv

m1m5dgzv3#

在逻辑运算的上下文中,除了零()之外的任何东西都是true,零是false
所以!1是“!true”是false
!0为“!false”为true
)任何类型的零:NULL计为零,0.0计为零

uemypmqf

uemypmqf4#

想想看,ok有一个布尔值,在初始化时是false。
(In c,0的值为false,我假设您知道这一点。)
在do while中,它只是对逻辑值取反,它仍然表示NOT。如果条件为真,它将循环,否则,它将不循环。
如果ok的值为假,你求反它,它就会为真,循环就会,嗯,循环。
我希望你能明白我的意思,它没有别的意思。

相关问题