Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding max value of char in C

I am finding the maximum value of a char by simple addition and testing for when the number goes negative:

#include<stdio.h>

/*find max value of char by adding*/
int main(){
  char c = 1;

  while(c + 1 > 0)
    ++c;

  printf("Max c = %d\n",(int)c);  /*outputs Max c = -128*/
  return 0;
}

The while loop tests ahead, so the first time c+1 is negative it breaks and we print the value of c. However, the programming is outputting the negative number!

Why doesn't this program output 127?

like image 453
user1717828 Avatar asked Jul 25 '16 19:07

user1717828


People also ask

What is the max value of char C ++?

Maximum value of unsigned char in C++ Unsigned char data type in C++ is used to store 8-bit characters. A maximum value that can be stored in an unsigned char data type is typically 255, around 28 – 1(but is compiler dependent).

What is the maximum value of string in C?

The maximum length of a string literal allowed in Microsoft C is approximately 2,048 bytes.

What is the maximum int value in C?

Value of INT_MAX is +2147483647. Value of INT_MIN is -2147483648.

How to find maximum occurring character in a string in C?

Write a C Program to Find Maximum Occurring Character in a String with example. This program allows the user to enter a string (or character array). Next, it will find the maximum occurring character (most repeated character) inside a string. First, we declared a Freq array of size 256, which will initially hold 0’s.

What is the maximum value that can be stored in Char?

A maximum value that can be stored in a signed char data type is typically 127, around 27 – 1 (but is compiler dependent ). The maximum and minimum value that can be stored in a signed char is stored as a constant in climits header file and can be named as SCHAR _ MAX and SCHAR_MIN respectively.

What is the max value of unsigned char in C++?

A maximum value that can be stored in an unsigned char data type is typically 255, around 28 – 1 (but is compiler dependent). The maximum value that can be stored in an unsigned char is stored as a constant in the <climits> header file, whose value can be used as UCHAR _ MAX.

How do you find the maximum of an array in C?

C programming code to find maximum using function. Our function returns index at which maximum element occur. int find_maximum(int[], int); int c, array[100], size, location, maximum; printf("Input number of elements in arrayn"); scanf("%d", &size);


Video Answer


1 Answers

There is an implicit cast occurring in the while conditional which is causing the comparison to work on ints rather than chars.

If you change it to

while((char)(c + 1) > 0)
    ++c;

then it will print 127.

like image 62
bgoldst Avatar answered Sep 29 '22 05:09

bgoldst