2,365 views
4 4 votes
int main()

    {
    char ch=1;

    while(ch<256)
    ch++;

    printf("Loop end");

    return 0;
    }

what will be output?

2 Answers

Best answer
2 2 votes

Char is 1 Byte. There are three distinct types of char in c99 standard. 

char , signed char,unsigned char

default char can be either signed or unsigned. It is implementation specific.For gcc, the default is signed.

In decimal notation value of a signed char can vary from $+(2^{n-1} -1)$ to $-(2^{n-1})$

which is (+127 to -128).

So after ch becomes 127 (01111111) then ch++ makes the value to (10000000) = -128 (2's complement form)

=> ch values rotate between (127  to -128). While condition always satisfied.

=> INF loop. nothing printed.

--------------------------------

In gcc we can use -funsigned-char flag during compilation time  which makes default char unsigned.

Now char range becomes (0 to +255) i.e. if ch = 255 at some point, ch++ makes ch=0

=> ch values rotate between (0 to +255), While condition always satisfied.

=> INF loop. nothing printed.

--------------------------------

conclusion : irrespective of implementation of default char sign (signed/unsigned). Nothing will be printed.

selected by
1 1 vote
Range of character varies from machine to machine...lets us take it as 1 byte..so the range of character is from -128 to +127 as msb is used for signed..

so ch get value 1 and then increamented till 127 and in the next itteration it will again -128 which will obviously<256 ,so it will go to infinite loop and thus "Loop end "will not be printed.

p.s-:please insert  check printf"hello"  inside the while loop which will verify you the infinite loop
Position:
Show:

Related questions

8 8 votes
6 6 answers
953
953 views
GO Classes asked Jul 25, 2025
953 views
#include <stdio.h void fun() { static int count = 0; count++; printf("%d ", count); } int main() { for (int i = 0; i < 3; i++) fun(); return 0; }What is the output of the...
5 5 votes
3 3 answers
672
672 views
GO Classes asked Jul 25, 2025
672 views
Given the pseudocode below for the function remains(), which of the following statements is true about the output, if we pass it a positive integer $n>2$ ? int remains(in...
6 6 votes
4 4 answers
733
733 views
GO Classes asked Jul 19, 2025
733 views
int arr[ ]={1, 2, 3, 4} int count; incr( ) {return ++count;} main( ) { arr[count++]=incr( ); printf("arr[count]=%d\n", arr[count]); }The value printed by the above progra...