Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 285
coder_12 Avatar asked May 09 '26 07:05

coder_12


2 Answers

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.

like image 97
HolyBlackCat Avatar answered May 11 '26 20:05

HolyBlackCat


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;
like image 23
paxdiablo Avatar answered May 11 '26 21:05

paxdiablo