From a syntax viewpoint, P4 is very close to C. It's quite a simple language. It's also very constrained in what it can do. Why so? Well, you have to think that you need to these P4 programs at line rate, possibly at terabits per second, so you really only have a few nanoseconds per packet to do processing before the next packet hits you. So you cannot start with fancy computation there. You are limited by design.
When you buy one of these switches, when you take it out of the box it cannot do a single thing. It cannot forward any packet. It does not know what the packet is. As you will see in the P4 code, we have to define what is the Ethernet header. What are the bits in the Ethernet header? Where is the source address, where is the destination address?
It may look like a lot of work but what it allows you to do is then to actually define your own protocol. So there are people who are using these switches for instance in special contexts like high frequency trading where instead of having IP destination there you could use stock ID, for instance. This is just one example. But it's just to tell you that you are not bound by having Ethernet and IP and TCP and UDP. You can create whatever you want!
So it gives you a lot of flexibility. You could create IPv5, IPv8, IPv10. If you wanted to do that without P4, the alternative would be to go and knock at the routing vendors doors and say, would you mind implementing me a switch that can forward this arcane protocol that no one cares about except me? Of course, they will say no to you.
Let me now switch to the code, and I will show you how it looks like.