{"id":72902,"date":"2023-04-24T09:01:08","date_gmt":"2023-04-24T09:01:08","guid":{"rendered":"https:\/\/www.cryptocabaret.com\/?p=72902"},"modified":"2023-04-24T09:01:08","modified_gmt":"2023-04-24T09:01:08","slug":"c-vs-go-comparing-programming-languages","status":"publish","type":"post","link":"https:\/\/www.cryptocabaret.com\/?p=72902","title":{"rendered":"C vs. Go: Comparing programming languages"},"content":{"rendered":"<p><span class=\"field field--name-title field--type-string field--label-hidden\">C vs. Go: Comparing programming languages<\/span><br \/>\n<span class=\"field field--name-uid field--type-entity-reference field--label-hidden\"><a title=\"View user profile.\" href=\"https:\/\/opensource.com\/users\/jim-hall\" class=\"username\">Jim Hall<\/a><\/span><br \/>\n<span class=\"field field--name-created field--type-created field--label-hidden\">Mon, 04\/24\/2023 &#8211; 03:00<\/span><\/p>\n<div class=\"clearfix text-formatted field field--name-body field--type-text-with-summary field--label-hidden field__item\">\n<p>Go is a modern programming language that derives much of its history from the C programming language. As such, Go is likely to feel familiar to anyone who writes programs in C. <a href=\"https:\/\/opensource.com\/article\/17\/6\/getting-started-go\">Go makes it easy to write new programs<\/a> while feeling familiar to C programmers but avoiding many of the common pitfalls of the C programming language.<\/p>\n<p>This article compares a simple C and Go program that adds the numbers from one to ten. Because this program uses only small values, the numbers won&#8217;t grow to be too big, so they only use plain integer variables. Loops like this are very common in programming, so this simple program makes it easy to compare C and Go.<\/p>\n<h2>How to do loops in C<\/h2>\n<p>The basic loop in C is the <code>for<\/code> loop, which allows you to iterate through a set of values. The basic syntax of the <code>for<\/code> loop is:<\/p>\n<blockquote>\n<p>for (<em>start condition<\/em> ; <em>end condition<\/em> ; <em>action after each iteration<\/em>) { <em>things to do inside the loop<\/em> ; }<\/p>\n<\/blockquote>\n<p>You can write a <code>for<\/code> loop that prints the numbers from one to ten by setting the starting condition to <code>count = 1<\/code> and the ending condition to <code>count . That starts the loop with the <code>count<\/code> variable equal to one. The ending condition means the loop continues as long as the <code>count<\/code> variable is less than or equal to ten.<\/code><\/p>\n<p>After each iteration, you use <code>count = count + 1<\/code> to increment the value of the <code>count<\/code> variable by one. Inside the loop, you can use <code>printf<\/code> to print the value of the <code>count<\/code> variable:<\/p>\n<pre>\n<code>for (count = 1; count <\/code><\/pre>\n<p>A common convention in C programming is <code>++<\/code>, which means &#8220;add one to something.&#8221; If you write <code>count++<\/code>, that&#8217;s the same as <code>count = count + 1<\/code>. Most C programmers would use this to write the <code>for<\/code> loop using <code>count++<\/code> for the action after each iteration, like this:<\/p>\n<pre>\n<code>for (count = 1; count <\/code><\/pre>\n<p>Here&#8217;s a sample program that adds the numbers from one to ten, then prints the result. Use the <code>for<\/code> loop to iterate through the numbers, but instead of printing the number, add the numbers to the <code>sum<\/code> variable:<\/p>\n<pre>\n<code>#include <stdio.h>\n\nint main() {\n  int sum;\n  int count;\n  puts(\"adding 1 to 10 ..\");\n  sum = 0;\n\n  for (count = 1; count <\/stdio.h><\/code><\/pre>\n<p>This program uses two different C functions to print results to the user. The <code>puts<\/code> function prints a string that&#8217;s inside quotes. If you need to print plain text, <code>puts<\/code> is a good way to do it.<\/p>\n<p>The <code>printf\u00a0<\/code><a href=\"https:\/\/www.redhat.com\/sysadmin\/command-basics-printf?intcmp=7013a000002qLH8AAM\" rel=\"noopener\" target=\"_blank\">function<\/a> prints formatted output using special characters in a format string. The <code>printf<\/code> function can print lots of different kinds of values. The keyword <code>%d<\/code> prints a decimal (or integer) value.<\/p>\n<p>If you compile and run this program, you see this output:<\/p>\n<pre>\n<code>adding 1 to 10 ..\nThe sum is 55<\/code><\/pre>\n<h2>How to do loops in Go<\/h2>\n<p>Go provides <code>for<\/code> loops that are very similar to C <code>for<\/code> loops. The for loop from the C program can be directly translated to a Go <code>for<\/code> loop with a similar representation:<\/p>\n<pre>\n<code>for count = 1; count <\/code><\/pre>\n<p>With this loop, you can write a direct transition to Go of the sample program:<\/p>\n<pre>\n<code>package main\nimport \"fmt\"\n\nfunc main() {\n  var sum, count int\n  fmt.Println(\"adding 1 to 10 ..\")\n\n  for count = 1; count <\/code><\/pre>\n<p>While the above is certainly a valid and correct Go, it&#8217;s not the most idiomatic Go. To be idiomatic is <em>to use expressions that are natural to a native speaker<\/em>. A goal of any language is effective communication, this includes programming languages. When transitioning between programming languages, it is also important to recognize that what is typical in one programming language may not be exactly so in another, despite any outward similarities.<\/p>\n<p>To update the above program using the more idiomatic Go, you can make a couple of small modifications:<\/p>\n<ol type=\"1\">\n<li>\n<p>Use the <code>+=<\/code> <em>add-to-self<\/em> operator to write <code>sum = sum + count<\/code> more succinctly as <code>sum += count<\/code>. C can use this style, as well.<\/p>\n<\/li>\n<li>\n<p>Use the <a href=\"https:\/\/go.dev\/ref\/spec#Short_variable_declarations\" rel=\"noopener\" target=\"_blank\">assign-and-infer-type operator<\/a> to say <code>count := 1<\/code> rather than <code>var count int<\/code> followed by <code>count = 1<\/code>. The <code>:=<\/code> syntax both defines and initializes the count variable.<\/p>\n<\/li>\n<li>\n<p>Move the declaration of <code>count<\/code> into the <code>for<\/code> loop header itself. This reduces a bit of cognitive overhead, and increases readability by reducing the number of variables the programmer must mentally account for at any time. This change also increases safety by declaring variables as close as possible to their use and in the smallest scope possible. This reduces the likelihood of accidental manipulation as the code evolves.<\/p>\n<\/li>\n<\/ol>\n<p>The combination of the changes described above results in:<\/p>\n<pre>\n<code>package main\nimport \"fmt\"\n\nfunc main() {\n  fmt.Println(\"adding 1 to 10 ..\")\n  var sum int\n  for count := 1; count <\/code><\/pre>\n<p>You can experiment with this sample program in the Go playground <a href=\"https:\/\/go.dev\/play\/p\/pt5mfRDR0rh\" rel=\"noopener\" target=\"_blank\">with this link to go.dev<\/a>.<\/p>\n<\/p>\n<div class=\"callout-float-right embedded-resource-list\" data-analytics-region=\"sidebar\">\n<div class=\"field field--name-title field--type-string field--label-hidden field__item\">Programming and development<\/div>\n<div class=\"field field--name-links field--type-link field--label-hidden field__items\">\n<div class=\"field__item\"><a href=\"https:\/\/developers.redhat.com\/?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"Red Hat Developers Blog\">Red Hat Developers Blog<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/downloads\/cheat-sheets?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"Programming cheat sheets\">Programming cheat sheets<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/www.redhat.com\/en\/services\/training\/learning-subscription?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"Try for free: Red Hat Learning Subscription\">Try for free: Red Hat Learning Subscription<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/downloads\/bash-programming-guide?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"eBook: An introduction to programming with Bash\">eBook: An introduction to programming with Bash<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/developers.redhat.com\/cheat-sheets\/bash-shell-cheat-sheet?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"Bash shell scripting cheat sheet\">Bash shell scripting cheat sheet<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/developers.redhat.com\/e-books\/modernizing-enterprise-java?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"eBook: Modernizing Enterprise Java\">eBook: Modernizing Enterprise Java<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/downloads\/building-applications?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"An open source developer's guide to building applications\">An open source developer&#8217;s guide to building applications<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/console.redhat.com\/?intcmp=7016000000127cYAAQ\" data-analytics-category=\"resource list\" data-analytics-text=\"Register for your free Red Hat account\">Register for your free Red Hat account<\/a><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<h2>C and Go are similar, but different<\/h2>\n<p>By writing the same program in two programming languages, you can see that C and Go are similar, but different. Here are a few important tips to keep in mind when transitioning from C to Go:<\/p>\n<ul>\n<li>\n<p>In C, every programming instruction must end with a semicolon. This tells the compiler where one statement ends and the next one begins. In Go, semicolons are valid but almost always inferred.<\/p>\n<\/li>\n<li>\n<p>While most modern C compilers initialize variables to a zero value for you, the C specification says that variables get whatever value was in memory at the time. Go values are always initialized to their zero value. This helps make Go a more memory safe language. This distinction becomes even more interesting with pointers.<\/p>\n<\/li>\n<li>\n<p>Note the use of the Go package specifier on imported identifiers. For example, <code>fmt<\/code> for functions that implement formatted input and output, similar to C&#8217;s <code>printf<\/code> and <code>scanf<\/code> from <code>stdio.h<\/code>. The <code>fmt<\/code> package is documented in <a href=\"https:\/\/pkg.go.dev\/fmt\" rel=\"noopener\" target=\"_blank\">pkg.go.dev\/fmt<\/a>.<\/p>\n<\/li>\n<li>\n<p>In Go, the <code>main<\/code> function always returns with an exit code of 0. If you wish to return some other value, you must call <code>os.Exit(n)<\/code> where <em>n<\/em> is typically 1 to indicate an error. This can be called from anywhere, not just <code>main<\/code>, to terminate the program. You can do the same in C using the <code>exit(n)<\/code> function, defined in <code>stdlib.h<\/code>.<\/p>\n<\/li>\n<\/ul>\n<\/div>\n<div class=\"clearfix text-formatted field field--name-field-article-subhead field--type-text-long field--label-hidden field__item\">\n<p>Use a simple counting program to compare the venerable C language with modern Go.<\/p>\n<\/div>\n<div class=\"field field--name-field-lead-image field--type-entity-reference field--label-hidden field__item\">\n<article class=\"media media--type-image media--view-mode-caption\">\n<div class=\"field field--name-field-media-image field--type-image field--label-hidden field__item\">  <img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/www.cryptocabaret.com\/wp-content\/uploads\/2023\/04\/collab-team-pair-programming-code-keyboard.png\" width=\"520\" height=\"292\" alt=\"Pair programming\" title=\"Pair programming\"><\/div>\n<div class=\"field field--name-field-caption field--type-text-long field--label-hidden caption field__item\"><span class=\"caption__byline\">Image by: <\/span><\/p>\n<p>WOCinTech Chat. Modified by Opensource.com. CC BY-SA 4.0<\/p>\n<\/div>\n<\/article>\n<\/div>\n<div class=\"field field--name-field-tags field--type-entity-reference field--label-hidden field__items\">\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/tags\/go-programming-language\" hreflang=\"en\">Go programming language<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/tags\/programming\" hreflang=\"en\">Programming<\/a><\/div>\n<\/p><\/div>\n<div class=\"hidden field field--name-field-listicle-title field--type-string field--label-hidden field__item\">What to read next<\/div>\n<div class=\"field field--name-field-default-license field--type-list-string field--label-hidden field__item\"><a rel=\"license\" href=\"http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/\"><br \/>\n        <img decoding=\"async\" alt=\"Creative Commons License\" src=\"https:\/\/www.cryptocabaret.com\/wp-content\/uploads\/2023\/04\/cc-by-sa--34.png\" title=\"This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.\"><\/a>This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.<\/div>\n<section class=\"field field--name-field-comments field--type-comment field--label-hidden comment-wrapper\">\n<div class=\"comments__count\">\n<div class=\"login\"><a href=\"https:\/\/opensource.com\/user\/register?absolute=1\">Register<\/a> or <a href=\"https:\/\/opensource.com\/user\/login?current=\/feed&amp;absolute=1\">Login<\/a> to post a comment.<\/div>\n<\/p><\/div>\n<\/section>\n<p class=\"wpematico_credit\"><small>Powered by <a href=\"http:\/\/www.wpematico.com\" target=\"_blank\" rel=\"noopener\">WPeMatico<\/a><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>C vs. Go: Comparing programming languages Jim Hall Mon, 04\/24\/2023 &#8211; 03:00 Go is a modern programming language that derives much of its history from the C programming language. As such, Go is likely to feel familiar to anyone who writes programs in C. Go makes it easy to write new programs while feeling familiar [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":72903,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[307],"tags":[],"class_list":["post-72902","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-open-source"],"_links":{"self":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts\/72902","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=72902"}],"version-history":[{"count":0,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts\/72902\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/media\/72903"}],"wp:attachment":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=72902"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=72902"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=72902"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}