<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shehab Khaled on Medium]]></title>
        <description><![CDATA[Stories by Shehab Khaled on Medium]]></description>
        <link>https://medium.com/@shehab299?source=rss-d3c897f06917------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hqZyiExn8lsU1KSX_lZa8A.jpeg</url>
            <title>Stories by Shehab Khaled on Medium</title>
            <link>https://medium.com/@shehab299?source=rss-d3c897f06917------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:35:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shehab299/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Linux Graphics: All the Layers You Didn’t Need (Until You Did)]]></title>
            <link>https://medium.com/@shehab299/linux-graphics-all-the-layers-you-didnt-need-until-you-did-d6893f6998a8?source=rss-d3c897f06917------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6893f6998a8</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[vulkan]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[graphics]]></category>
            <dc:creator><![CDATA[Shehab Khaled]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 00:00:15 GMT</pubDate>
            <atom:updated>2026-09-21T00:04:38.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2nlEMXFXSmCIfka-9O1kQ.png" /></figure><blockquote>How does an image actually travel from your code to your monitor?</blockquote><p>Linux graphics stack can feel like a pile of unrelated names: framebuffer, DRM, KMS, Xorg, Wayland, Mesa, OpenGL, Vulkan, and so on.</p><p>Memorizing definitions does not help much. Instead, let us build the stack from scratch and introduce each piece only when we actually need it.</p><h3>1. Bare-metal System</h3><p>Assumptions for our system are as follows:</p><pre>1. No GPU<br>2. No operating system<br>3. CPU <br>4. RAM<br>5. A display controller capable of driving a monitor<br>6. HDMI Cable<br>7. Monitor</pre><p>Let’s first define what a framebuffer is because we will need it</p><blockquote>A <strong>framebuffer</strong> is simply a region of memory that contains the pixels to appear on the screen.</blockquote><p>For a basic 32-bit RGBA image, each pixel may occupy four bytes: one byte each for red, green, blue, and alpha. A program can create an image simply by writing the desired values into this memory.</p><p><strong>The journey</strong> from software to screen looks like this:</p><ol><li>The <strong>CPU</strong> writes pixel values into a region of <strong>RAM</strong>.</li><li>That region acts as a <strong>framebuffer</strong>.</li><li>The CPU configures the<strong> display controller</strong> with information such as the framebuffer address, resolution, pixel format, and timing.</li><li>The display controller repeatedly reads the framebuffer.</li><li>It generates the correctly timed <strong>HDMI</strong> display signal.</li><li>The <strong>monitor</strong> receives the signal and displays the image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*ktC2zaYILh4QPVlLGZ1Fvg.png" /></figure><p>Please keep this distinction in mind:</p><blockquote><strong>Rendering</strong> produces pixel values in memory.</blockquote><blockquote><strong>Scanout</strong> reads completed pixel data and sends it toward the display.</blockquote><p>That is it. The CPU renders the image, and the display controller scans it out. The framebuffer itself does not draw or display anything. It is just memory.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>2. What changes when Linux enters the picture?</h3><p>Now let us add Linux and ruin this beautiful simplicity.</p><p><strong>In the</strong> <strong>bare-metal case</strong>, our program controlled everything.</p><p><strong>On Linux</strong>, a normal userspace application cannot simply control the display-controller. The kernel owns and protects the hardware. Applications request operations through kernel interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*swwTi9LSeaiPXSjvu8PpJg.png" /></figure><p>On Linux, display hardware is commonly managed through the <strong>DRM (Direct Rendering Manager) </strong>subsystem.</p><p>Despite the name, <strong>DRM</strong> is not just about rendering. But let’s leave that for later. Let’s now talk about <strong>KMS</strong></p><h3>Kernel Mode Setting</h3><p>The display-management part of DRM is called <strong>Kernel Mode Setting (KMS)</strong></p><p><strong>KMS</strong> manages resources such as:</p><ul><li><strong>Connectors </strong>such as HDMI or DisplayPort</li><li><strong>CRTCs </strong>which generate display timings and scanout</li><li><strong>Framebuffers</strong> which describe buffers that can be scanned out</li><li>Display modes, such as 1920 × 1080 at 60 Hz</li></ul><p>DRM devices are exposed through files under /dev/dri</p><p>For example:</p><pre>/dev/dri/card0</pre><p>A program can open this file and communicate with the driver using system calls, especially ioctl().</p><p>This is what a minimal DRM/KMS program such as <a href="https://gist.github.com/shehab299/9d224e11de5e45aa46a386d58a3bc911">draw_drm.c</a> does. It discovers a display, allocates or obtains a buffer, fills it with pixels, creates a DRM framebuffer object, and asks KMS to scan it out.</p><p>Such an experiment normally needs to run from a text console with suitable permissions and without another application controlling the same display.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>3. Display Servers entering the Scene</h3><p>Up to this point, we were able to draw something on the screen from Linux.</p><p>But our program has effectively taken ownership of the whole display. This is fine if we are living in the 1980s and our computer’s entire job is to show one magnificent fullscreen spreadsheet. But we typically need to display many applications at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GNHeWn8ILIdw9F0EKdaJWA.gif" /></figure><p>But, we do not want every application independently fighting over changing display modes and replacing the scanout framebuffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*geuRGuJYelFOm-fv94TDaw.png" /></figure><p>Instead, we will have one privileged component owning the physical display and applications communicating with it to provide their window contents.</p><p>That one privileged component is the <strong>Display Server</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*4yPnAAcVGzFVHKk9viojnw.png" /></figure><p>Two major protocol families occupy this space on Linux: <strong>X11</strong> and <strong>Wayland</strong>.</p><h3>1) The X Window System</h3><p><strong>X11</strong> is version 11 of the X protocol. An X11 application is called an <strong>X client</strong>, and it communicates with an <strong>X server</strong>. The X.Org Server is the reference implementation for the server</p><pre>       Firefox (X11 client)<br>          │<br>          │ X11 protocol<br>          |<br>          |<br>          ▼<br>       Xorg server</pre><p>The X11 core protocol was designed when computers looked very different from today. Computers changed dramatically, but replacing the entire protocol every few years would have been a disaster. Instead, new functionality was added through extensions.</p><p>Examples include extensions for modern input, rendering, shared memory, direct rendering, and efficient presentation.</p><h3>Traditional server-side rendering</h3><p>In the traditional X model, an application could send drawing requests to the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*r8bSUMqkNjjBVNusl2LChQ.png" /><figcaption>Traditional server-side rendering model</figcaption></figure><p>This design also made X naturally <strong>network-transparent</strong>.</p><p>Well I am not trying to be a smarty-pants here. I just found “network-transparent” a nice concept so let’s learn the definition together</p><blockquote><strong>Network transparent</strong> means a system works the same way whether two components are on the <strong>same machine or connected over a network</strong>.</blockquote><h3>Modern client-side rendering</h3><p>Modern applications usually render most of their contents on their own.</p><p>Remember the distinction?</p><blockquote><strong>Rendering </strong>is producing pixel values in memory</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*qJ4CCzYWJr726AmT5cTX9A.png" /><figcaption>modern client-side rendering model</figcaption></figure><p>The application is no longer asking the X server to draw every button, letter, and image. It renders a window-sized buffer and asks the X system to present it.</p><p>Now let us look at Wayland.</p><h3>2) Wayland</h3><p>First, <strong>Wayland is a protocol</strong>, not a specific program. A program implementing the server side of that protocol is called a <strong>Wayland compositor</strong>.</p><ul><li><strong>Weston</strong> is the reference implementation for a Wayland compositor</li><li>Need another example? <strong>KWin</strong> (part of KDE Plasma)</li></ul><p>Applications (<strong>Wayland clients</strong>) render their own window contents into buffers. They then attach those buffers to Wayland surfaces and commit them. <strong>The Wayland compositor</strong> then combines the surfaces into one and presents the result to the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6ggjMQKkrGw7YMfulGRnA.png" /><figcaption>Wayland Model</figcaption></figure><p>Unlike the X protocol, Wayland’s core protocol does not provide commands such as “draw this”. Applications are expected to render their own content.</p><p><strong>Now let’s talk compatibility</strong>! What happens for applications targeting <strong>X Window System</strong>?</p><h3>Running X11 applications under Wayland</h3><p>Existing X11 applications can run in a Wayland session through <strong>XWayland</strong>.</p><p><strong>XWayland</strong> acts as both:</p><ul><li>An <strong>X server</strong> from the <strong>X11</strong> application’s perspective</li><li>A <strong>Wayland client</strong> from <strong>the Wayland compositor</strong>’s perspective</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*9r853-6S_jqQ-ydwtdmEGA.png" /><figcaption>XWayland Model</figcaption></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>4. Adding a GPU</h3><p>A <strong>GPU</strong> (Graphics Processing Unit) is a specialized processor for massively parallel graphics computation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUTF6-99pS799xatPFU4rg.png" /></figure><p>So now as you can see that the <strong>Display Controller</strong> is often a part of the GPU. Which doesn’t make a difference. <strong>So what does adding a GPU really change?</strong></p><p>It changes <strong>who renders the damn pixels. </strong>Let’s explain that!</p><p>So far, we have assumed that the CPU renders every pixel. That<strong> old path</strong> looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*Bq00gMarKWq0ZRIIgheK7w.png" /></figure><p>As you can see, the CPU performs two expensive jobs:</p><ol><li><strong>Application rendering</strong>: producing the contents of each window.</li><li><strong>Composition</strong>: combining multiple windows into the desktop image.</li></ol><p>But we know that a <strong>GPU</strong> is designed to execute large numbers of graphics and compute operations in parallel. So what about offloading both jobs to its <strong>rendering engine</strong></p><p>Let’s now look at the <strong>new path</strong></p><p>For example, Firefox can send rendering commands to the GPU. The GPU executes them and produces a buffer containing the browser window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*fuhk_XMlnHWV7iMCcqdcCw.png" /><figcaption>GPU Rendering</figcaption></figure><p>The compositor can then use the GPU to combine that buffer with the terminal, editor, wallpaper, cursor, and other surfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*2mfaHwu7otXkG9hxVC_b2Q.png" /><figcaption>GPU Composition</figcaption></figure><p>I think we are quite done here! Except we quietly cheated. <strong>Where do OpenGL, Vulkan, and Mesa fit into this picture?</strong></p><p>To answer that, we first need a different question: <strong>how does an application actually talk to the GPU?</strong> Remember what happened with the display controller? Linux won’t let us just talk to its GPU directly.</p><h3>How does a userspace program access the GPU?</h3><p>Remember when I said <strong><em>“DRM isn’t just about display” </em></strong>? This is the <strong>“later”</strong>. Once again, Linux provides the kernel-side infrastructure through DRM.</p><p>Until now, we mostly discussed DRM display functionality:</p><pre>DRM<br> └── KMS<br>      └── display configuration and scanout</pre><p>With GPU rendering included, the picture becomes broader:</p><pre>DRM<br> ├── KMS<br> │    └── display configuration and scanout<br> │<br> └── GPU Rendering and Compute Engine Management</pre><p>So, in short:</p><blockquote><em>KMS controls what is scanned out to a display. The rendering side of DRM provides kernel infrastructure that userspace drivers use to operate the GPU.</em></blockquote><h3>DRM Devices</h3><p>Let’s revisit our draw_drm.c program. Back then we opened</p><pre>open(&quot;/dev/dri/card0&quot;, O_RDWR);</pre><p>Once we add a GPU, look at /dev/dri on your machine. On my machine which has two graphics devices, the directory look like this:</p><pre>$ ls -l /dev/dri<br><br>crw-rw----+ 1 root video 226,   0 Sep 17 17:16 card0<br>crw-rw----+ 1 root video 226,   1 Sep 17 17:16 card1<br>crw-rw-rw-  1 root video 226, 128 Sep 17 17:16 renderD128<br>crw-rw-rw-  1 root video 226, 129 Sep 17 17:16 renderD129</pre><p>As we can see we have two <strong>DRM devices</strong> and each appears to expose both <strong>a primary node</strong> and <strong>render node</strong></p><pre>Graphics Device A<br>├── card0<br>└── renderD128</pre><pre>Graphics Device B<br>├── card1<br>└── renderD129</pre><p>What is the difference between <strong>primary nodes</strong> and <strong>render nodes?</strong></p><h3>Primary nodes: card&lt;N&gt;</h3><p>Primary nodes are located at paths such as:</p><pre>/dev/dri/card0</pre><p>They expose privileged device functionality, including KMS display control. This is why draw_drm.c opened a primary node.</p><pre>Display program<br>      │<br>      ▼<br>/dev/dri/card0<br>      │<br>      ▼<br>DRM driver and KMS<br>      │<br>      ▼<br>Display Controller</pre><h3>Render nodes: renderD&lt;N&gt;</h3><p>Render nodes are located at paths such as:</p><pre>/dev/dri/renderD128</pre><p>They provide access to rendering functionality without exposing display mode setting. They do not let an application take over a monitor.</p><pre>          Application <br>              │<br>              ▼<br>      /dev/dri/renderD128<br>              │<br>              ▼<br>        DRM GPU driver<br>              │<br>              ▼<br>     GPU rendering engine</pre><h3>The GPU Dilemma</h3><p>Can an application just open /dev/dri/renderD128 and tell the GPU what to draw? <strong>Not really</strong>.</p><p>DRM does not provide a simple interface like this:</p><pre>drmDrawTriangle(...);<br>drmDrawRectangle(...);<br>drmRunShader(...);</pre><p>That’s because every GPU family works differently. Each has its own instructions and its own way of accepting commands. So each kernel driver adds its own GPU-specific interface on top of the common DRM code.</p><p>If applications talked to those interfaces directly, every app would need separate code for Intel, AMD, NVIDIA, and every other GPU. We definitely don’t want this:</p><pre>Application<br> ├── Intel-specific GPU code<br> ├── AMD-specific GPU code<br> └── NVIDIA-specific GPU code</pre><p>Instead, applications use common graphics APIs such as <strong>OpenGL</strong> or <strong>Vulkan</strong>.</p><p>Worth mentioning that <strong>OpenGL</strong> and <strong>Vulkan</strong> are only specifications. They define the API and the behavior applications can expect, but they contain no code. Someone still has to implement them.</p><h3><strong>Userspace Graphics Driver</strong></h3><p>That someone who implements them is <strong>a userspace graphics driver</strong></p><p>The application calls the API, and the driver translates those calls into commands for the installed GPU, then submits them to the kernel. Here is the full path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XW8xkqPUOZJ7EXe2G9nIQ.png" /></figure><p>Several projects fill this role:</p><ul><li><strong>Mesa</strong> is the open-source implementation most Linux systems use. It provides OpenGL and Vulkan drivers for many GPUs.</li><li><strong>Proprietary drivers</strong>, such as NVIDIA’s, ship their own OpenGL and Vulkan implementations.</li></ul><p>This separation is what allows the same OpenGL application to run on different hardware without containing every GPU’s native command language itself.</p><h3>11. The complete picture</h3><p>We finally have all the pieces. Let us trace one frame from a modern Wayland application all the way to the monitor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGAvezTN3kGo_tBqu9HOCQ.png" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Final mental model</h3><p>If you leave this article with only four ideas, remember these:</p><ol><li>A <strong>framebuffer</strong> is memory holding pixels; <strong>rendering</strong> fills it and <strong>scanout</strong> displays it.</li><li><strong>DRM</strong> is Linux’s kernel graphics subsystem, while <strong>KMS</strong> is its display-management component.</li><li>A display server (Ex: <strong>X.Org</strong>) owns the display so multiple applications can share it.</li><li>Every GPU speaks its own language. <strong>OpenGL and Vulkan</strong> are specifications that give applications one common API, and <strong>userspace drivers</strong> like <strong>Mesa</strong> translate it for the installed GPU.</li></ol><blockquote>And here, ladies and gentlemen, our journey with the Linux graphics stack ends.</blockquote><blockquote>We started with a pile of unrelated names: framebuffer, DRM, KMS, Xorg, Wayland, Mesa, OpenGL, Vulkan. Now each one has a job.</blockquote><blockquote>Next time your screen lights up, you’ll know how it got there. Thanks for reading!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6893f6998a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Big Deal With Types In Programming]]></title>
            <link>https://medium.com/@shehab299/the-big-deal-with-types-in-programming-752d4db4048c?source=rss-d3c897f06917------2</link>
            <guid isPermaLink="false">https://medium.com/p/752d4db4048c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[datatypes-in-javascript]]></category>
            <dc:creator><![CDATA[Shehab Khaled]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 14:52:03 GMT</pubDate>
            <atom:updated>2024-08-07T03:25:35.429Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently found myself in the midst of writing JavaScript functions into C++ and using the Emscripten compiler to bring it all together. As I navigated this process, it became clear just how crucial types are in programming. Types aren’t just a minor detail—they’re fundamental to what we do — that’s why I decided to write this blog, let’s tackle data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*yn2zcBXV3ksnMLq1" /></figure><h3>What Are Types?</h3><p>When you write code, you’re creating a program. But what happens when you run this code? It transforms into something more dynamic — a process. The operating system, acting as the maestro of your computer, assigns a portion of memory to this process.</p><blockquote>Process: a running program</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*GB-4-99UIi60ZrYkEbgjXQ.png" /></figure><p>So you have this pool of bits that represents data, and you are mainly concerned with dealing with this data. But how will you deal with them? Will you deal with individual bits?</p><p>Absolutely not! If I gave you a big block of text, would you be concerned with each character, or would you group them into chunks that represent valuable information?</p><p>Of course, you would group the characters into words and sentences. The same is true for programs. They will group bits into chunks representing different pieces of information that you can move around and operate on.</p><blockquote><strong>Value</strong>: A chunk of data that you can move around and operate on.</blockquote><p>But there is another question here: Will you operate on these chunks in the same way?</p><p>Of course not, because if you want one chunk to represent the number 3 and another chunk to represent the word “Chocolate,” you can’t operate on them in the same way! So these chunks should have types associated with them.</p><p><strong>Note: As I said, each program is given a block of memory that it can do whatever it wants with. So it is up to the program to interpret these chunks the way it wants. That’s why programming languages have different types, and that’s why you need to be careful when integrating different programming languages.</strong></p><h3>Example</h3><p>To demonstrate this idea of different types let’s look at two popular programming languages and how they represent numbers</p><ul><li><strong>C++</strong></li></ul><p>In c++ numbers are represented with specific types</p><ul><li>int : representing signed integer number in 32bit chunks</li><li>float : representing floating point number in 32bit chunks</li><li>double : representing floating point numbers in 64bit chunks</li></ul><p>— — — — — — — — — — — —</p><ul><li><strong>JavaScript</strong></li></ul><p>In JavaScript you have only one type to represent both floating point and integer numbers</p><ul><li>Number : representing numbers in 64bit chunks</li></ul><h3>Expressions And Statements</h3><p>I just want you to know the difference between expressions and statements.</p><blockquote>Expressions: Any valid unit of code that resolves to a value</blockquote><p>Examples:</p><pre>(2 + 3) * 5;<br><br>2 * add(2, 3);</pre><blockquote>Statements: A statement mainly is an instruction that performs an action. they often contain expressions and mainly they make up the actual steps in your code.</blockquote><p>Examples:</p><pre>var x; // define the variable x</pre><h3>Static and Dynamic Typing</h3><p>Look at these two exciting programs</p><ul><li>JavaScript</li></ul><pre>var x = 5;<br>var y;<br><br>if(x == 5)<br> y = &quot;shehab&quot;;<br>else<br> y = 2;</pre><ul><li>C++</li></ul><pre>int x = 5;<br>string y;<br><br>if(x == 5)<br>  y = &quot;shehab&quot;; // Compile Error<br>else <br>  y = 5;</pre><p>Interestingly the first program will run just fine but the second program won’t even compile why is that exactly?</p><p><strong>C++ is what we call a statically typed language.</strong></p><blockquote>Statically Typed Language : Language where types associated with each variable are known and checked in compile time.</blockquote><p>That means before your program runs the compiler already knows that the variable y will be only associated with strings and you can’t assign it to an integer.</p><p>You might interrupt me and ask what about the auto keyword in c++.</p><pre>auto x = 5;</pre><p>will you didn’t tell the compiler what type but the compiler inferred it so that doesn’t contradict what we say.</p><p><strong>JavaScript doesn’t work that way. It is a dynamically typed language</strong></p><blockquote>Dynamically Typed Language: type checking takes place at run time</blockquote><p>As a result of that variables aren’t the ones associated with types like c++ but only the values are the ones associated with types.</p><p>(Focus on the difference between values and variables)</p><h3>Coercion (implicit conversion)</h3><blockquote>Coercion: Implicit conversion happens when the compiler automatically converts one data type to another without explicitly instructing it to.</blockquote><p>Let’s give you an example about what that is</p><ul><li>C++</li></ul><pre>double a = 1.2;<br>int b = 1;<br><br>double c = a + b;</pre><p>In this example, a is represented in memory as a 64-bit number (double), while b is a 32-bit integer. How does the computation happen? The compiler automatically coerces (converts) b into a double, then performs the operation. But why does it choose double over integers? These conversions are defined by the language specification, so it’s always important to refer to the spec.</p><p>so will c++ allow you to do whatever you want. Try this</p><pre>int x = 3 + &quot;3&quot;;</pre><p>The compiler will literally yell at you.</p><p>C++ is somewhat strict about its types, but it’s also a bit permissive in certain situations.</p><ul><li><strong>JavaScript</strong></li></ul><p>Try these examples to see how JavaScript handle coercion</p><pre>var result = &#39;5&#39; + 2; <br><br>// coerce 2 to &#39;2&#39; and concatenate &#39;5&#39; and &#39;2&#39; to &#39;52&#39;<br><br>var result = &#39;5&#39; - 2; <br>// coerce &#39;5&#39; to 5 and do the operation (5 - 2) to 3<br><br>if(0) <br>// will coerce 0 to false</pre><p>So JavaScript is much more permissive than c++. However, JavaScript’s permissiveness has limits. Consider the following code</p><pre>var x = 5;<br>x(); <br><br>// TypeError: x isn&#39;t a callable object and javascript doesn&#39;t define this <br>// convertion from numbers to callable objects</pre><p>Programming languages like C++ and JavaScript have different levels of strictness and permissiveness regarding types and coercion.</p><h3>Type Strictness</h3><p>since programming languages have different levels of strictness. let’s try to visually represent these levels using a scale</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*3omYpBR1hIAR4ojdNGM4xQ.png" /><figcaption>Strictness Scale</figcaption></figure><p>At the top of the scale, there are languages we call strongly typed languages, which in theory won’t allow any type to be converted to any type implicitly.</p><p>At the bottom of the scale, there are languages we call weakly typed languages, which in theory will allow any type to be converted to any type implicitly.</p><p>Any programming language that positions itself between these two types is somewhat weakly typed and strongly typed at the same point but tends more toward one of them according to where they lie on the scale.</p><p>Example:</p><ul><li>C++ is close to strongly typed languages but it also has little permissiveness</li><li>JavaScript is more close to weakly typed languages but it has a little bit of strictness</li></ul><h3>Conclusion</h3><blockquote>Watch your language</blockquote><p>I mean watch how your language deals with its types. Understanding a language’s type system is key to writing robust and reliable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=752d4db4048c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveling Up C With A Plus]]></title>
            <link>https://medium.com/@shehab299/leveling-up-c-with-a-plus-20420617d6a2?source=rss-d3c897f06917------2</link>
            <guid isPermaLink="false">https://medium.com/p/20420617d6a2</guid>
            <category><![CDATA[data-structres]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Shehab Khaled]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 18:29:13 GMT</pubDate>
            <atom:updated>2024-04-20T18:48:48.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveling Up C With A Plus: Implementing OOP principles in C</h3><h3>Introduction</h3><p>Recently, I have been working on a college project that implements a process scheduler. I needed to write several data structures like queues and heaps, as a person who spent his entire coding era — not that much — using objects. I have stumbled on how to implement the same principles in c. So I did some digging and made this blog. So follow along, if you are interested of course!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6azIEDKXuZ4OgsPz5BXyg.jpeg" /></figure><h3>what will we do</h3><p>We will spend this tutorial using a dummy data structure called Coco<br>we will implement it first in C++ using OOP principles and then move it to C preserving its functionality and design principles.</p><h3>C++ Implementation</h3><pre>class Coco<br>{<br> <br>private:<br>  int milk;<br><br>  void changeMilk(int amount)<br>  {<br>     milk += amount;<br>  }<br> <br>public:<br>  <br>  Coco(){<br>     this-&gt;milk = 50;<br>  }<br><br>  void addMilk(){<br>   changeMilk(10);<br>  }<br><br>  void removeMilk(){<br>   changeMilk(-10);<br>  }<br><br>  ~Coco(){}<br><br>}</pre><p>In the Coco class, we’ve applied several object-oriented programming principles:</p><ol><li><strong>Encapsulation</strong>: <br> The class hides its internal data “milk” and implementation details (such as the “changeMilk” method) from external code. This helps prevent direct data manipulation and ensures that the class maintains its integrity.</li><li><strong>Abstraction</strong>: <br>The class abstracts away the complexities of its implementation. External users only need to interact with the public methods “addMilk” and “removeMilk” without needing to understand how these methods are implemented internally.</li></ol><h3>Migration To C</h3><p>let’s encapsulate our data in one place like what we did in C++<br>we will use a struct</p><pre>struct Coco{<br>  int milk;<br>};</pre><p>What about our functions what will we do with it? Think about this. finished thinking? No?</p><p>I meant the this. The pointer “this”. you might remember that “this” is a pointer that C++ implicitly passes to every little member function in your class and points to the object you are working with.</p><p>so let’s do the same in c except that we will make it explicit. Our functions will take the first parameter as a pointer to a Coco.</p><pre>Choco* createCoco(){<br> return (Choco*) malloc(sizeof(Choco));<br>}<br><br>void addMilk(Coco* c){<br> changeMilk(c,10);<br>}<br><br>void removeMilk(Coco* c){<br> changeMilk(c,-10);<br>}<br><br>void changeMilk(Coco* c, int amount){<br> c-&gt;milk += amount;<br>}<br><br>Choco* destory(Coco* c){<br> free(c);<br>}</pre><p><strong>Are we done yet?</strong> Of course not. I wouldn’t take an hour from my time to only write this. Think about the problems that are in front of us, or not I will tell you anyway.</p><h3>Problems so fat 😅 (A funny typo)</h3><p><strong>Direct Access to Data Members</strong>: Anyone can access the `milk` data member directly using the pointer to `Coco`. We want to make it private to prevent impolite access.</p><ol><li><strong>Direct Access to Private Helper Function</strong>: Our beloved “changeMilk” function is meant to be a private helper function. But anyone curious enough will easily use it.</li><li><strong>Direct Access to Data Members</strong>: Anyone can access the “milk” data member directly using the pointer to “Coco”. We want to make it private to prevent impolite access.</li></ol><h3>How will we solve these problems?</h3><h4><strong>First</strong>: Separation interface from implementation.</h4><p>we’ll separate the interface from the implementation by creating two files: “ Coco.h ” and “ Coco.c ”. In Coco.h, we’ll declare the function declarations that we want external code to be able to access. In Coco.c, we’ll provide the implementation of these, including private functions.</p><pre>#file: Choco.h<br><br>typedef struct{<br> int milk;<br>} Choco;<br><br><br>Choco* createChoco();<br><br>void addMilk(Choco* c);<br><br>void removeMilk(Choco* c);<br><br>Choco* destory(Choho* c);<br></pre><pre>#file: Choco.c<br><br>#include &quot;Choco.h&quot;<br><br>Choco* createChoco(){<br> return (Choco*) malloc(sizeof(Choco));<br>}<br><br>void addMilk(Choco* c){<br> changeMilk(c,10);<br>}<br><br>void removeMilk(Choco* c){<br> changeMilk(c,-10);<br>}<br><br>void changeMilk(Choco* c, int amount){<br> c-&gt;milk += amount;<br>}<br><br>Choco* destory(Choho* c){<br> free(c);<br>}</pre><p>Voila, now a polite programmer won’t be able to use changeMilk directly.</p><h4><strong>Second</strong>: Using opaque pointers</h4><ul><li>What is an opaque pointer</li></ul><blockquote>Obaque: not able to be seen through; not transparent.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*10PuhIspfL04dF4C9o-HRw.jpeg" /><figcaption>What It Means To Be Opaque</figcaption></figure><p>An opaque pointer is a pointer that hides its internal structure.</p><ul><li>How can we implement this?</li></ul><p><strong>let’s talk technical first:</strong> it is often implemented using a forward declaration of a struct in the header file, with the actual struct definition hidden in the implementation file.</p><p><strong>Enough with definitions, let’s talk code: </strong>in the .h file change the struct to this:</p><pre>#Coco.h<br><br>struct Coco;<br><br>rest of the file....</pre><p>And put the actual structure in “Coco.c”. Isn’t that the same as the<br>first step? yes, it is. (just fancy words)</p><p><strong>So can you see it now? S</strong>ince only what we define in .h is visible to the user and we didn’t define the internal structure of the struct there, now no one can see it (no one polite)</p><p><strong>You might be asking</strong> ( I hope not )</p><ul><li>Question: wouldn’t that make a problem for our functions because they try to access the data members of the struct?</li><li>Answer: did you forget that they are in the same place as the struct?</li></ul><h3><strong>Where are we now?</strong></h3><p>we are actually at the end of this blog and we successfully managed to migrate the code from C++ to C or should we call it coding in C+</p><blockquote>see you in another tutorial. — Me</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20420617d6a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>