You are not logged in.

#1 2023-03-26 08:11:26

Baird
Member
Registered: 2023-03-10
Posts: 11

array[idx] = idx++; , in C++ and in C

I read some books about C++ recently.

Now I know that array[idx] = idx++;" is undefined in C++.

Is that rule is same in C?

Is there some common behavior in most compilers?

Sorry for my poor English.

Offline

#2 2023-03-26 10:24:13

seth
Member
Registered: 2012-09-03
Posts: 51,046

Re: array[idx] = idx++; , in C++ and in C

Now I know that array[idx] = idx++;" is undefined in C++.

That is, at least w/o context, complete nonsense.

#include <stdio.h>
int main()
{
    int array[8];
    int idx = 0;
    while (idx < 8)
        array[idx] = idx++;
    for (int i = 0; i < 8; ++i)
        printf("%d: %d ", i, array[i]);
}

is gonna compile and run fine and valid C and C++ but will leave you w/ an undefine array[0]

=> Post the actual code example you concern.

Offline

#3 2023-03-26 10:45:55

3beb6e7c46a615a
Member
Registered: 2021-03-27
Posts: 165

Re: array[idx] = idx++; , in C++ and in C

seth wrote:

Now I know that array[idx] = idx++;" is undefined in C++.

That is, at least w/o context, complete nonsense.

I don't think it is.  I don't remember the exact details of sequencing in C++, but I believe the given expression is unsequenced and would thus constitute undefined behaviour. At least, "idx = idx++" is definitely unsequenced, and I don't think that array access forces sequencing here.

Whether the compiler accepts the code bears no relevance to whether its behaviour is defined.

Offline

#4 2023-03-26 11:22:40

seth
Member
Registered: 2012-09-03
Posts: 51,046

Re: array[idx] = idx++; , in C++ and in C

The expression is defined, but the array access doesn't add a sequence point (-Wall); both alterations remain side effects, regardless of the C/C++ standard.

So yes, the actually expectable behaviour is undefined - everywhere.
"Common behavior in most compilers" (which should™ have hinted me at what the OP was after) doesn't matter because it could (theoretically) change tomorrow and if you don't care about equal behavior under *all* circumstances, you can just as much roll w/ the behavior in front of you - otherwise simply avoid this if you need to predict the compiler behavior on random systems.

Offline

Board footer

Powered by FluxBB