A
A
Aviare2015-03-16 00:02:52
Programming
Aviare, 2015-03-16 00:02:52

The ternary operator behaves strangely in C. What's the problem?

I decided to play around a bit with the for loop and the ternary conditional operator.
The program must find the minimum and maximum in an array of randomly given numbers. However, not only does it search badly, but also the variable either min or max takes a very large or very small value (for example, 1590569472 or -688611888)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
#define RANDMAX 100

int main()
{
    srand (time(NULL));
    int a[N], i, max, min;
    for (i = 0, a[N]; i < N; printf ("%3d", a[++i] = rand()%RANDMAX));
    for (max = a[0], i = 1; i < N; (max = (max < a[i]) ? a[i]: max), i++);
    for (min = a[0], i = 1; i < N; (min = (min > a[i]) ? a[i]: min), i++);
    printf ("\n Max: %d\n Min: %d\n", max, min);
    return 0;
}

I am using ubuntu 14.04, gcc 4.8.
Examples of what I get when I run the program.
[email protected]:~/amaproga$ ./stih
 28 88 78 72 69 35 11  3 45 92
 Max: 88
 Min: -542684176
[email protected]:~/amaproga$ ./stih
  9 23 14 80  3  4 20 48 30 42
 Max: 1213853936
 Min: 3
[email protected]ustme:~/amaproga$ ./stih
 68 46 77 71 51 82 62 66 55 55
 Max: 1436604496
 Min: 46
[email protected]:~/amaproga$ ./stih
 31 55 60 31 94 26 26 37 65 11
 Max: 94
 Min: -1571974768
[email protected]:~/amaproga$ ./stih
 31 55 60 31 94 26 26 37 65 11
 Max: 94
 Min: -1921410176
[email protected]:~/amaproga$ ./stih
 37 51 51 96 23 89 31  2 53  3
 Max: 96
 Min: -1506582624

Explain, please, in what a problem. And, if possible, tell me how to fix it. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Puma Thailand, 2015-03-16
@aviare

you use ++i during initialization,
as a result a[0] is not initialized and consists of garbage,
so also go beyond the array at the end

E
Evsign, 2015-03-16
@Evsign

Go beyond the boundaries of arrays, as conditions are in the loop header. At the last iteration, the 10th cell is accessed (you only have 0..9 elements), and only then the condition is checked and the loop exits.

K
KorsaR-ZN, 2015-03-16
@KorsaR-ZN

Everything is right with you, it is enough to replace only ++i with i++
The only thing is that you have a bad programming style.
Don't do that, don't try to shorten the syntax, people can read after you.
It won't matter to the compiler whether you write it this way or a complete analogue through a normal loop and a full-fledged IF, and your program will become clear, easy to read and maintain from this.
PS about the difference between ++i and i++ , read in google , it will immediately become clear what your mistake was.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question