int a=-3,b=2,c=0,d;
d=++a&&++b||++c;
printf("a=%d,b=%d,c=%d,d=%d",a,b,c,d);

why value of 'c' is not incremented in output?

Dani AI

Generated

Short answer: and are correct — c is not incremented because of operator precedence and short‑circuit evaluation. The expression groups as (++a && ++b) || ++c (because && binds tighter than ||). ++a changes a from -3 to -2 (non‑zero, true), so ++b runs and makes b = 3; the && then yields true. Because the left side of || is true, the right side (++c) is not evaluated, so c stays 0 and d gets 1. Expected values: a = -2, b = 3, c = 0, d = 1.

Key details to note: pre‑increment returns the incremented value and any nonzero integer is treated as true. Logical && and || evaluate left operand first and short‑circuit the right operand when the result is already determined; the result of logical operators in C is 1 (true) or 0 (false). See authoritative notes on operator precedence, , and order of evaluation/sequence rules.

Practical advice: avoid packing side effects (pre/post increments) inside boolean expressions — it reduces readability and can hide subtle sequencing issues. Increment variables on separate lines, then combine the resulting values in a clear boolean expression. Also remember that modifying the same object more than once without a sequencing relation is undefined behavior, so keep side effects simple and well ordered.

Recommended Answers

All 2 Replies

Because a and b were successfully incrementented? You have putten an 'conditional or' operator between the two statements. Although I am not an C expert, usually, when the first part appears to be true the second part will not performed at all.

Correct C#Jaap, the logical and (&&) and or (||) operators use shortcut evaluation, that is if they can determin the result after evaluating the left hand expression they do not bother evaulating the right hand expression. For && this means if the left hand expression is false the right hand expression is not evaluated and for || this means if the left hand expression is true the right hand expression is not evaluated.

It means things like you can safely test a pointer and dereference it in the same if statement

if (valid != 0 && (*valid) != 0)
{
  // Its valid
}
else
{
  // Its not valid or valid is NULL which is also probably not valid
}   
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.