How are text messages (SMS) sent to an iPhone received in a Mac? I want to know the working of the program. When an SMS is sent to the iPhone, does it upload after receiving it on the phone to the iCloud, which then syncs it to the mac or does is it received directly by the mac independent of the phone?
In the first case, it would mean that the phone needs internet connection for the messages to be received on the Mac, whereas, in the second case, it would mean that messages are sent to Apple's server by the service provider. Or does it have any other mechanism?
The setting "Text Message Forwarding" on your iPhone uploads/broadcasts all text messages to all verified devices through iCloud.

Your iPhone needs data for this, obviously. Your carrier has nothing do to with this.

All devices need to be logged in to iCloud using the same Apple ID for this to work. Also, you need to verify each device as you enable them in your iPhone's settings.

This setting is part of Apple's Continuity feature set.