6

Can a variable be used when reporting?

 3 years ago
source link: https://www.codesd.com/item/can-a-variable-be-used-when-reporting.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Can a variable be used when reporting?

advertisements

Why does the following compile without an error?:

int main()
{
    int x = x;  //I thought this should cause an error
    return 0;
}

Where in the standards is it explained why this is allowed?


This question has a slightly different answer in C than in C++.

In both cases, int x = x; tries to initialize x with itself.


In C++: [dcl.init]/12 (N3936) says that any evaluation of an object with indeterminate value causes undefined behaviour, except for certain cases involving unsigned char. In fact there is an Example:

int f(bool b) {
    unsigned char c;
    unsigned char d = c; // OK, d has an indeterminate value
    int e = d;        // undefined behavior
    return b ? d : 0; // undefined behavior if b is true
}


In C: It is more complicated. This is very similar to the behaviour of int b; foo(b - b); which is covered in full here.

I won't repeat that text but the conclusions are, in C11:

  • int a = a; &a; causes UB if and only if the system has trap representations for int
  • int a = a;, with no subsequent occurrence of &a, causes UB.

Historical note: In C90 this caused UB. In C99 the trap representation was introduced, and in C11 the possibility of register trap was introduced (for Itanium). The C++ standard doesn't deal with trap representations at all, it seems underspecified in the case of things like bitwise operators generating negative zero.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK