user7023473
user7023473

Reputation:

How can I write a program to find maximum value of integer variable

In C, how can I write a program to find the maximum value of an integer variable? As far as I know the maximum value of an integer variable is 2147483647 but how can I represent this in a C program ?

Upvotes: 3

Views: 6824

Answers (4)

Ajay
Ajay

Reputation: 11

I know it is late, but if one has to calculate as an assignment, one can use sizeof() operator and this will give the number of bytes an integer holds.

2^((number of bytes*8) - 1) should give the max value of an integer.

Of course sizeof()too is compile time just like INT_MAX.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476950

You cannot find this value programatically by means of computation. There is no way to detect that you're "at the end", and incrementing the largest integer has undefined behaviour.

That's why the largest and smallest values of integral types are made available to you by the standard library in the <limits.h> header. It is your responsibility to ensure that the results of operations fit into the desired types.

Upvotes: 7

Peter H
Peter H

Reputation: 901

The maximum and minimum values are defined in limits. You can verify these using the following code.

C Version:

#include <stdio.h>
#include <limits.h>


int main()
{
    printf("Minimum Int value:%d\n", INT_MIN);
    printf("Minimum Int value:%d\n", INT_MAX);
    return 0;
}

In C++

#include "stdafx.h"
#include <iostream>
#include <limits>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Minimum Int value:" << INT_MIN << endl;
    cout << "Maximum Int value:" << INT_MAX << endl;
    return 0;
}

An alternate (Non Visual Studio Version is below):

#include <iostream>
#include <string>
#include <limits.h>
using namespace std;
int main()
{
    std::cout << "Minimum Int value:" << INT_MIN << endl;
    std::cout << "Maximum Int value:" << INT_MAX << endl;
}

The constant names E.G INT_MIN and INT_MAX can be found in the website below if you are interesting in the maximum values and minimum values of other data types.
http://www.cplusplus.com/reference/climits/

Upvotes: 3

P.P
P.P

Reputation: 121357

As ı know the maximum value of a integer variable is 2147483647

That's a wrong assumption. The maximum value of an int can vary across systems. For example, on a 16-bit machine maximum value of int is not 2147483647.

You don't need to find it yourself. There are pre-defined macros which you can use from <limits.h>. For example, INT_MAX represents the maximum value an int can hold.

Upvotes: 10

Related Questions