Tuesday Coding Tip 11 — null-coalescing operator

3 9 47
calendar_todayschedule1 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 19 of 20 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 17 — Wrapping C APIs

Jakub Neruda - Jun 30

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9
chevron_left
1.2k Points59 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
24Posts
19Comments
12Connections
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)

5 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!