difask's blog

By difask, 11 years ago, In English

Hello everyone! Some days ago I noticed one very useful trick in C++. It works in GNU. I think it will work in VS too. Many coders use macro "#define INF 1000000007", as very large number, larger then possible answer. I notice that instead of writing it, we can write INFINITY and it will the maximal of current type. For example:

  1. ll ans = INFINITY; //long_long_max

  2. if (smth < INFINITY) //int_max by default

  3. if (smth < (long long)INFINITY) //long_long_max

I have never seen it in codes. Maybe for someones it will be useful.

  • Vote: I like it
  • +35
  • Vote: I do not like it

»
11 years ago, hide # |
Rev. 3  
Vote: I like it +14 Vote: I do not like it

It's not so useful. For example long long answer = INFINITY; if (answer == INFINITY) // answer != INFINITY

  • »
    »
    11 years ago, hide # ^ |
     
    Vote: I like it +2 Vote: I do not like it

    Yes, in this case it will not work. But it is possible to write

     if (answer == (ll)INFINITY)
    

    And it will work correctly.

»
11 years ago, hide # |
Rev. 2  
Vote: I like it +22 Vote: I do not like it

That is not really useful because you usually want to have INFINITY/2 and not INFINITY itself, since any addition will overflow type. In other words you really don't want inequalities INF+5<INF to be correct.

»
11 years ago, hide # |
 
Vote: I like it +6 Vote: I do not like it

I use (1 << 30) for int. And (1ll << 60) for long long type.

»
11 years ago, hide # |
 
Vote: I like it +5 Vote: I do not like it

As Shtrix stated too , it's not really useful because you simply can not do any addition to the value correctly , but if you insist on using this , I'd choose the safer way :

    int minn = numeric_limits<int>::max()/4;
    long long maxx = numeric_limits<long long>::min()/4 ;