Shaurya Uppal
Shaurya Uppal

Reputation: 3690

Is using #define and typedef with data type a good practice?

I wanted to know is using

#define ll long long
typedef long long ll;

A good practice, I adopted it few weeks ago after looking at codes of top red coder in codeforces.

Also please explain the difference b/w typedef and #define because everywhere I have studied or spotted these it , they work alike.

Explain #define and typedef use and difference?

Also is it good to use, does the runtime get reduced even if it does get reduced by 0.0000001 second ,please tell.

Upvotes: 2

Views: 328

Answers (3)

Richard Hodges
Richard Hodges

Reputation: 69902

Fundamentally, the problem with #define has nothing to do with compiler performance.

It has everything to do with clobbering the programming environment in ways that are hard to debug.

contrived example:

#include <iostream>

#define while if

int main()
{
    int i = 10;
    while (i) {
        std::cout << i-- << std::endl;
    }
}

What does this program do?

What would someone who is casually reading the program expect it to do?

Upvotes: 0

didiz
didiz

Reputation: 1099

Basically one should avoid #define it is not type checked, and the compiler does not see it.

Using a typedef for a basic type is not best practice as well.

However, both have their uses, #define when you want to do something before compilation, such as leaving out debug code in release mode, and typedef which can improve readability when using some longer STL constructs.

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76438

In general, use language constructs rather than pre-processor constructs. The problem with the macro is that every use of ll that follows the definition of that macro will get replaced:

void f() {
    int ll = 3; // whoops, error
}

With the typedef that code is okay.

Upvotes: 5

Related Questions