简体   繁体   English

C 中没有赋值或语句的数字

[英]Numbers without assignment or statement in C

What happens to the values or text without assignment.没有赋值的值或文本会发生什么。 How does compiler handle them?编译器如何处理它们? Do they impact performance of the code (What does the CPU/processor do with them)?它们是否会影响代码的性能(CPU/处理器对它们有什么作用)?
Here is the example code: I just put 3, 5 and "abcd", code doesn't throw any error.这是示例代码:我只输入了 3、5 和“abcd”,代码不会抛出任何错误。

int main() 
{
    // Here I declared the variables
    int a, b;
    
    // Here there are some numbers
    3;
    5;
    "abcd";
    
    return 0;
}

The compiler will tell you:编译器会告诉你:

<source>:9:5: warning: expression result unused [-Wunused-value]

If the expression result is not used then the compiler will not generate any resulting code.如果不使用表达式结果,则编译器将不会生成任何结果代码。 It is very likely that the string literal will be not present in the object and executable files字符串文字很可能不会出现在 object 和可执行文件中

As @EricPostpischil stated if the expression fas side effect it will be evaluated.正如@EricPostpischil 所说,如果表达式有副作用,它将被评估。

examples:例子:

p++;
1 + foo(p);
1 + p++;
foo(p);

also if you declare objects as side effects prone this kind of expressions will be evaluated.另外,如果您将对象声明为容易产生副作用的对象,则将评估这种表达式。

example例子

    volatile int a, b;
    a;  //this will generate the code
    b;  //this will generate the code

https://godbolt.org/z/fa4sa51nq https://godbolt.org/z/fa4sa51nq

C 2018 6.8.3 says: C 2018 6.8.3 说:

The expression in an expression statement is evaluated as a void expression for its side effects.表达式语句中的表达式因其副作用而被评估为 void 表达式。

Thus no use is made of the value.因此没有使用该值。 Only side effects are useful.只有副作用是有用的。 In a statement such as printf("Hello, world.\n");在诸如printf("Hello, world.\n");这样的语句中, a so-called side effect is to send the string to standard output. ,所谓的副作用是将字符串发送到标准output。

Statements such as 3; 3; and 5;5; have no side effects, and the main value is ignored, so they have no effects.没有副作用,并且忽略了主要值,因此它们没有任何影响。

All expression statements you think of as “doing something”, such as:您认为是“做某事”的所有表达式语句,例如:

printf("x = %d.\n", x);
b = 4;
FindMatchingThings(a, b, c);
++y;

actually do those things by way of their side effects: Sending data to a stream, updating the value of an object, or calling a function which has its own side effects.实际上是通过它们的副作用来做这些事情:将数据发送到 stream,更新 object 的值,或者调用具有自身副作用的 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM