IIFE for Complex Initialization -- Bartlomiej Filipek

filipek-iife.pngWhat do you do when the code for a variable initialization is complicated? Do you move it to another method or write inside the current scope? Bartlomiej Filipek presents a trick that allows computing a value for a variable, even a const variable, with a compact notation.

IIFE for Complex Initialization

by Bartlomiej Filipek

In this article:

I hope you’re initializing most variables as const (so that the code is more explicit, and also compiler can reason better about the code and optimize).

For example, it’s easy to write:

const int myParam = inputParam * 10 + 5; 

or even:

const int myParam = bCondition ? inputParam*2 : inputParam + 10; 

But what about complex expressions? When we have to use several lines of code, or when the ? operator is not sufficient.

‘It’s easy’ you say: you can wrap that initialization into a separate function.

While that’s the right answer in most cases, I’ve noticed that in reality a lot of people write code in the current scope. That forces you to stop using const and code is a bit uglier.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.