Tuesday Coding Tip 11 — null-coalescing operator

●5 ●23 ●87
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Some languages, like C# or Javascript, have a special operator ?? which is a specialization over the normal ternary operator. It either returns the value of the left operand or, if it is null, it returns the value of the right operand.

Furthermore, the ??= operator allows you to only assign to a variable if it is null. Syntax among languages might differ, so check out this overview: https://en.wikipedia.org/wiki/Null_coalescing_operator

var a = null;

// Initialize b with a, or with 42 if a is null
var b;
if (a == null) b = 42;
else b = a;

// Shorter version with ?? operator
var c = a ?? 42;

// Update a with something if it is null
a ??= 24;
Part 11 of 29 in Tuesday Coding Tips

1 Comment

2 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++

Jakub Neruda - Oct 20

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21
chevron_left
2k Points • 115 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
42Posts
35Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!