c++c++14preprocessor-directivelong-long

Using preprocessing directive #define for long long


#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 .


Solution

  • 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:

    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.