Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Output of C Program | Set 28

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Predict the output of following C program.

Question 1




#include <stdio.h>
  
int main()
{
    char a = 30;
    char b = 40;
    char c = 10;
    char d = (a * b) / c;
    printf ("%d ", d);
  
    return 0;
}


At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200. For example, the following code snippet prints -80 on a 32 bit little endian machine.

    char d = 1200;
    printf ("%d ", d);

Arithmetic overflow doesn’t happen in the original program and the output of the program is 120. In C, char and short are converted to int for arithmetic calculations. So in the expression ‘(a*b)/c’, a, b and c are promoted to int and no overflow happens.



Question 2




#include<stdio.h>
int main()
{
    int a, b = 10;
    a = -b--;
    printf("a = %d, b = %d", a, b);
    return 0;
}


Output:

a = -10, b = 9

The statement ‘a = -b–;’ compiles fine. Unary minus and unary decrement have save precedence and right to left associativity. Therefore ‘-b–‘ is treated as -(b–) which is valid. So -10 will be assigned to ‘a’, and ‘b’ will become 9.
Try the following program as an exercise.




#include<stdio.h>
int main()
{
    int a, b = 10;
    a = b---;
    printf("a = %d, b = %d", a, b);
    return 0;
}




Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 27 Dec, 2016
Like Article
Save Article
Similar Reads