0

The odd numbers array is grouped in this way: first number is the first group, the next 2 numbers form the 2nd group, the next 3 numbers form the 3rd group and so on.

Groups:

  1. 1
  2. 3 5
  3. 7 9 11
  4. 13 15 17 19
  5. 21 23 25 27 29

Now I want to find if a given number is the sum of the numbers in a group and find the order number of that group.

I wrote the next code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int k;
    scanf("%d", &k);

    int x = 1;
    while( x * x * x < k )
        x++;

    if( x * x * x != k )
        x = 0;

    printf("%d", x);
    return 0;
}

Then I tried to change the while loop to the next one:

while( x * x * x++ < k )
    ;

The program is not working and I get the next warning in codeblocks:

operation on 'x' may be undefined

Why does it is not working?

Timʘtei
  • 753
  • 1
  • 8
  • 21

1 Answers1

5

The behaviour of x * x++ is undefined. This is because you are essentially reading from and writing to x in an unsequenced step; multiplication is not a sequence point in C.

Don't do this in C. Your compiler is warning you of this out of common courtesy. Other compilers might eat your cat.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    `Other compilers might eat your cat.` I wasn't ready for that. You made my day xD – Darkpingouin May 24 '17 at 09:35
  • This has been asked a million times before. Instead of answering the same old question over and over, please vote to close it as duplicate. A list of good duplicates can be found here: https://stackoverflow.com/tags/c/info. In this case FAQ -> operators -> [Why are these constructs (using ++) undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior). – Lundin May 24 '17 at 09:41
  • @Lundin: The common duplicates on this are centred around the `=` operator, which is chiefly why I felt it appropriate to answer this one. `*` is more subtle, IMHO at least anyway. (And the reputation is immaterial: now I have the T shirt, the pen, and the mug ;-)) – Bathsheba May 24 '17 at 10:34
  • Could also use https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior or https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – Lundin May 24 '17 at 10:43
  • Alternatively you could just link to the C standard ;-). Personally I set the criteria for a duplicate as the *question* being an exact duplicate of another *question*. The fact that an answer to another question can serve to answer another question is not, to me at least, a test of "duplicateness". – Bathsheba May 24 '17 at 10:44