Using preprocessing directive #define for long long

8.1k Views Asked by At
#include <iostream>
using namespace std;
#define ll long long

int main() {
    
    int a = 5;
    ll maxi = 1;
    maxi = max(maxi, maxi * ll(a));
    cout<<maxi<<endl;
    return 0;
    
}

Why does this code throw an error? I don't understand what's wrong with #define ll long long .

3

There are 3 best solutions below

1
On BEST ANSWER

Remember that #define performs a textual substitution. You end up with this:

maxi = max(maxi, maxi * long long(a));

Which is invalid, since the type name for a functional cast can't, roughly speaking, contain spaces at the top level. So, unsigned int(a), long double(a), etc, are all invalid for this the same reason.

The solution is either to use using instead of #define:

using ll = long long;

or to do (ll)a, since in this case the spaces are allowed.

But if I were you, I would get rid of ll and use (long long)a, since ll is a rather non-descriptive name.


Note that #define ll long long is a misuse of macros, and is bad for many reasons:

  • It's confusing. From seeing ll maxi = 1;, a reasonable person would expect ll to be a type and ll(a) to work. And it would work if it wasn't a macro.

  • The short name can conflict with things. If you put this #define in a header, and then include another header that uses the word ll for any purpose whatsoever, it will break.

    To avoid that, macros should have long scary ALL_CAPS names.

Macros should be the last nuclear option, used when everything else fails, not just when you don't feel like typing some extra letters.

It's something you see on competitive programming sites, but if you attempted this at an actual job, it would fail any sane code review.

1
On

Remember the type casting method at first we have to write the typename first with the braces and then the variable like this (int)a.

In your code you have misused the macros.You have to write the keyword first then the thing by which you wanna call the keyword like this #define long long ll Then you can use long long as ll. That was all issues that you have with your code.

0
On

There's nothing wrong with #define ll long long (other than the possibility you'll confuse it with 11), it does exactly what it's supposed to do.

However, the cast ll(a), which translates to long long(a), is invalid (no spaces allowed in this form).

You need to use (ll)a, which becomes (long long)a.


I should mention that it would be better to use type definitions to do this rather than #define statements. That would be one of:

typedef long long ll
using ll = long long;