Kalana
Kalana

Reputation: 6143

How to understand Expressions?

I have done some experiments using expressions. When I am working with some code, I found this unusual thing.

    int i = 3;
    int j = 5;
    j >= i;

    printf("Output1 = %d\n", i);
    printf("Output2 = %d", j);

when I compiled this code I got error messge.

    int i = 3;
    int j >= i;

    printf("Output1 = %d\n", i);
    printf("Output2 = %d", j);

    return 0;

This also give me an error message.

    int i = 3;
    int j = 5 >= i;

    printf("Output1 = %d\n", i);
    printf("Output2 = %d", j);

1) If i <= 5 output will be

Output1 = 3                                                                                         
Output2 = 1

2) If i > 5 output will be

Output1 = 3                                                                                         
Output2 = 0

Why my first trial and second trials give errors and third one compiled unharmly?

I need some explanation.

Upvotes: 2

Views: 83

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753625

Converting comments into an answer.

In the first trial, the statement j >= i; has no effect on the computation so it is ignored by the compiler. Your compiler settings might convert that warning into an error, which is a Good Thing™.

The second trial is an outright syntax error. You can't use a comparison in place of an initializer.

The third trial is fine and gives the expected results. The value of a comparison such as 5 >= i is either 0 if the comparison is false or 1 if the comparison is true.

But in the third one, there is also a comparison in the initializer but it didn't give an syntax error or compile error

In the third one, you have:

int j = …something…;

which is a valid initializer (because the …something… is a valid comparison). Initializers start with an = symbol. In the second, you have nt j >= i; — this does not start with = and hence is invalid. Note that trying int j == i; would also be invalid; the symbol is == and not =.

See C11 §6.7.9 Initialization and §6.7 Declarations for the syntax of intializers.

Then it means comparison which is in initializer is true it outputs 1. If false it output 0.

Yes, the comparison in the initializer generates either 1 (true) or 0 (false) — that is the value assigned to j, as your tests showed.

Upvotes: 2

Related Questions